import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import '../models/user_model.dart';
import '../models/exam_model.dart';
import '../data/user_data.dart';
import '../services/exam_service.dart';
import '../services/exam_state_service.dart';
import '../services/exam_session_service.dart';
import '../services/photo_state_service.dart';
import '../services/auth_service.dart';
import 'exam_screen.dart';
import 'exam_rules_screen.dart';
import 'result_screen.dart';
import 'student_results_screen.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../services/user_log_service.dart';
import '../services/student_service.dart';
import '../services/device_config_service.dart';
import 'dart:convert';
import 'dart:io';
import '../services/dedicated_device_monitor_service.dart';
import '../models/student_model.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:flutter/services.dart';
import 'dart:async'; // 导入Timer
import 'dart:convert'; // 导入JSON解析
import 'package:intl/intl.dart'; // 导入日期格式化
import '../models/question_model.dart'; // 导入Question和QuestionType

// 简单的应用内日志收集器
class AppLogger {
  static final List<String> _logs = [];
  static const int maxLogs = 1000; // 最多保存1000条日志

  static void log(String message) {
    final timestamp = DateTime.now().toString().substring(0, 19);
    final logEntry = '[$timestamp] $message';

    _logs.add(logEntry);

    // 保持日志数量在限制内
    if (_logs.length > maxLogs) {
      _logs.removeAt(0);
    }

    // 同时输出到控制台
    debugPrint(message);
  }

  static List<String> getLogs() {
    return List<String>.from(_logs);
  }

  static void clearLogs() {
    _logs.clear();
  }
}

// 管理员密码已通过UserData.verifyAdminPassword()方法验证

class HomeScreen extends StatefulWidget {
  final int initialTab;
  final bool skipIncompleteExamCheck; // 新增参数，用于跳过未完成考试检查

  const HomeScreen({
    super.key,
    this.initialTab = 0, // 默认选择第一个标签
    this.skipIncompleteExamCheck = false, // 默认不跳过检查
  });

  @override
  State<HomeScreen> createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> with WidgetsBindingObserver {
  late User _currentUser;
  int _selectedIndex = 0;
  List<Exam> _exams = [];
  bool _isLoading = true;
  bool _isAdmin = false;
  final AuthService _authService = AuthService();
  
  // 辅助函数：获取头像图片提供者
  ImageProvider _getAvatarImage(String? avatarPath) {
    if (avatarPath == null || avatarPath.isEmpty) {
      return const AssetImage('assets/default_avatar.png');
    }
    if (avatarPath.startsWith('http')) {
      return NetworkImage(avatarPath);
    }
    return AssetImage(avatarPath);
  }
  // 调试模式标志，仅在开发环境中启用
  final bool debugMode = true;
  
  // 管理员自动登出相关变量
  Timer? _inactivityTimer;
  static const int _adminInactivityTimeout = 60; // 60秒无操作自动登出
  int _remainingSeconds = _adminInactivityTimeout;
  bool _showCountdown = false;
  // 移除GlobalKey，使用更安全的方式管理倒计时组件
  
  // 未完成考试相关
  List<Map<String, dynamic>> _incompleteExams = [];
  bool _hasIncompleteExams = false;
  DateTime? _lastCheckTime;
  // 密码输入控制器
  final TextEditingController _passwordController = TextEditingController();

  @override
  void initState() {
    super.initState();
    // 注册应用状态观察者
    WidgetsBinding.instance.addObserver(this);

    // 获取当前登录的用户
    _currentUser = UserData.currentUser ?? User.sampleUser();

    // 检查未完成的考试 - 根据参数决定是否立即检查
    if (!widget.skipIncompleteExamCheck) {
      _checkIncompleteExams();
    } else {
      debugPrint('跳过未完成考试检查（从结果页面返回）');
      // 延迟检查，给考试状态删除操作足够的时间
      Future.delayed(Duration(seconds: 3), () {
        if (mounted) {
          debugPrint('延迟检查未完成考试（3秒后）');
          _checkIncompleteExams();
        }
      });
    }

    // 初始化选中的标签页
    _selectedIndex = widget.initialTab;

    // 检查是否为管理员
    _checkAdminStatus();

    // 加载考试数据
    _loadExams();
  }
  
  @override
  void dispose() {
    // 移除应用状态观察者
    WidgetsBinding.instance.removeObserver(this);
    // 取消定时器
    _inactivityTimer?.cancel();
    // 释放控制器
    _passwordController.dispose();
    super.dispose();
  }
  
  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    // 管理员不需要自动退出逻辑，只有学生需要
    // 注释掉管理员的应用状态变化处理
    // if (_isAdmin) {
    //   if (state == AppLifecycleState.resumed) {
    //     _startInactivityTimer();
    //   } else if (state == AppLifecycleState.paused) {
    //     _inactivityTimer?.cancel();
    //   }
    // }

    // 当应用恢复到前台时，检查未完成的考试
    if (state == AppLifecycleState.resumed) {
      // 检查是否正在进行拍照操作
      final isPhotoInProgress = PhotoStateService().isTakingPhoto;
      debugPrint('主页面：应用恢复前台，拍照状态: $isPhotoInProgress');

      if (isPhotoInProgress) {
        debugPrint('检测到拍照操作进行中，跳过未完成考试检查');
        return;
      }

      // 延迟检查，给拍照操作一些时间完成状态更新
      Future.delayed(Duration(milliseconds: 500), () {
        if (mounted && !PhotoStateService().isTakingPhoto) {
          debugPrint('延迟检查：拍照已完成，开始检查未完成考试（从桌面恢复）');
          _checkIncompleteExams();
        } else {
          debugPrint('延迟检查：拍照仍在进行中，跳过检查');
        }
      });
    }
  }
  
  // 启动学生用户无操作退出计时器（管理员不使用）
  void _startInactivityTimer() {
    // 管理员不启动自动退出计时器
    if (_isAdmin) {
      return;
    }

    // 取消可能存在的定时器
    _inactivityTimer?.cancel();

    // 重置倒计时秒数
    _remainingSeconds = _adminInactivityTimeout;

    // 显示倒计时组件（如果还没显示）
    if (!_showCountdown) {
      setState(() {
        _showCountdown = true;
      });
    }

    // 倒计时逻辑现在完全由独立的CountdownWidget处理
    // 主页面不再需要定时器，避免页面刷新
  }
  
  // 用户交互时重置定时器（仅学生用户）
  void _resetInactivityTimer() {
    // 管理员不需要重置计时器
    if (_isAdmin) {
      return;
    }

    // 重置倒计时状态
    _remainingSeconds = _adminInactivityTimeout;
    _showCountdown = true;

    // 不再调用setState，避免页面刷新影响导航
    // 倒计时的UI更新由独立的CountdownWidget处理
  }
  
  // 自动登出操作（仅学生用户）
  void _autoLogout() async {
    // 管理员不自动登出
    if (_isAdmin) {
      return;
    }

    // 首先检查全局考试会话状态
    if (ExamSessionService().isInExam) {
      debugPrint('🎯 检测到全局考试会话，取消自动登出');
      _startInactivityTimer(); // 重新开始计时
      return;
    }

    // 检查是否有正在进行的考试，如果有则不自动登出
    final currentUser = UserData.currentUser;
    if (currentUser != null) {
      try {
        // 检查是否有活动的考试会话
        final hasActiveSession = await _checkForActiveExamSession();
        if (hasActiveSession) {
          // 有正在进行的考试，重置计时器而不是登出
          debugPrint('检测到正在进行的考试，取消自动登出');
          _startInactivityTimer(); // 重新开始计时
          return;
        }
      } catch (e) {
        debugPrint('检查活动考试会话时出错: $e');
      }
    }

    // 没有正在进行的考试，执行正常的自动登出
    UserData.logout();
    // 导航到登录页面
    Navigator.pushReplacementNamed(context, '/login');

    // 显示消息（虽然在导航后不会显示，但为了安全起见）
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text('由于长时间无操作，您已被自动登出'))
    );
  }
  
  // 检查是否有活动的考试会话
  Future<bool> _checkForActiveExamSession() async {
    try {
      final currentUser = UserData.currentUser;
      if (currentUser == null) {
        return false;
      }

      // 首先检查当前路由，如果用户在考试页面，直接返回true
      final currentRoute = ModalRoute.of(context)?.settings.name;
      if (currentRoute == 'ExamScreen' || currentRoute == '/exam') {
        debugPrint('用户当前在考试页面，认为有活动会话');
        return true;
      }

      final prefs = await SharedPreferences.getInstance();
      final allKeys = prefs.getKeys();

      // 筛选出属于当前用户的考试状态键
      final userStateKeys = allKeys.where((key) =>
        key.startsWith('exam_state_') &&
        key.contains(currentUser.id)
      ).toList();

      // 检查每个考试状态是否有活动会话标记
      for (final key in userStateKeys) {
        try {
          final String? stateJson = prefs.getString(key);
          if (stateJson != null) {
            final Map<String, dynamic> stateMap = jsonDecode(stateJson);

            // 检查answers字段中是否有_active_session标记
            if (stateMap.containsKey('answers') && stateMap['answers'] is Map) {
              final Map<String, dynamic> answers = stateMap['answers'];
              if (answers.containsKey('_active_session') && answers['_active_session'] == true) {
                // 检查最后活动时间，如果是最近5分钟内的活动，认为是真正的活动会话
                DateTime? lastActivity;
                if (stateMap.containsKey('lastActivity')) {
                  try {
                    lastActivity = DateTime.parse(stateMap['lastActivity']);
                  } catch (e) {
                    // 如果解析失败，检查answers中的_last_activity
                    if (answers.containsKey('_last_activity') && answers['_last_activity'] is int) {
                      lastActivity = DateTime.fromMillisecondsSinceEpoch(answers['_last_activity']);
                    }
                  }
                }

                if (lastActivity != null) {
                  final timeDifference = DateTime.now().difference(lastActivity).inMinutes;
                  if (timeDifference < 5) {
                    debugPrint('发现最近活动的考试会话: $key (${timeDifference}分钟前)');
                    return true;
                  } else {
                    debugPrint('发现非活动的考试会话: $key (${timeDifference}分钟前)，不视为活动会话');
                  }
                } else {
                  debugPrint('发现活动考试会话但无活动时间: $key');
                  return true; // 如果没有活动时间，保守地认为是活动会话
                }
              }
            }
          }
        } catch (e) {
          debugPrint('解析考试状态出错: $key, 错误: $e');
          continue;
        }
      }

      return false;
    } catch (e) {
      debugPrint('检查活动考试会话时出错: $e');
      return false;
    }
  }
  
  Future<void> _checkAdminStatus() async {
    // 直接使用UserData.isAdminUser判断
    final isAdmin = UserData.isAdminUser;
    setState(() {
      _isAdmin = isAdmin;
    });
    
    // 管理员不启动自动退出计时器，只有学生需要
    // 注释掉管理员的自动退出逻辑
    // if (isAdmin) {
    //   _startInactivityTimer();
    //   // 立即显示倒计时
    //   setState(() {
    //     _showCountdown = true;
    //   });
    // }
  }
  
  Future<void> _loadExams() async {
    setState(() {
      _isLoading = true;
    });
    
    // 确保 ExamService 已初始化
    await ExamService.init();
    
    // 获取所有考试
    List<Exam> exams = ExamService.getAllExams();
    
    setState(() {
      _exams = exams;
      _isLoading = false;
    });
  }
  
  // 刷新用户信息（特别是学生的考试分配信息）
  void _refreshUserInfo() {
    final currentUser = UserData.currentUser;
    if (currentUser != null && currentUser != _currentUser) {
      setState(() {
        _currentUser = currentUser;
      });
      debugPrint('用户信息已刷新: ${_currentUser.name}');
      if (_currentUser is Student) {
        final student = _currentUser as Student;
        debugPrint('学生分配的考试ID: ${student.assignedExamId}');
      }
    }
  }

  void _onItemTapped(int index) {
    _resetInactivityTimer(); // 用户操作重置计时器
    
    // 学生用户只能导航到首页
    if (!_isAdmin && index != 0) {
      return; // 忽略非首页的导航请求
    }
    
    setState(() {
      _selectedIndex = index;
    });
  }

  void _logout() {
    // 显示确认退出对话框
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.logout, color: Colors.orange),
            SizedBox(width: 8),
            Text('确认退出登录'),
          ],
        ),
        content: Text('确定要退出登录吗？退出后需要重新登录。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context); // 关闭对话框
              // 注销登录
              UserData.logout();
              Navigator.pushReplacementNamed(context, '/login');
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.orange,
              foregroundColor: Colors.white,
            ),
            child: Text('确认退出'),
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // 每次build时检查用户信息是否需要更新
    _refreshUserInfo();
    
    return Listener(
      // 监听所有触摸事件，重置无操作计时器
      onPointerDown: (_) => _resetInactivityTimer(),
      onPointerMove: (_) => _resetInactivityTimer(),
      onPointerUp: (_) => _resetInactivityTimer(),
      child: WillPopScope(
        onWillPop: () async {
          // 重置计时器
          _resetInactivityTimer();
          // 阻止用户通过系统返回按钮返回到登录页面
          // 可以提示用户使用退出登录功能
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(content: Text('请使用退出登录功能退出应用')),
          );
          return false; // 阻止返回
        },
        child: Scaffold(
          appBar: AppBar(
            title: const Text('考培系统'),
            backgroundColor: Colors.blue.shade800,
            foregroundColor: Colors.white,
            actions: [
              // 显示学生用户倒计时（管理员不显示）
              if (!_isAdmin && _showCountdown)
                Flexible(
                  flex: 1,
                  child: Container(
                    constraints: BoxConstraints(maxWidth: 80), // 限制最大宽度
                    child: _IndependentCountdownWidget(
                      initialSeconds: _adminInactivityTimeout,
                      onTimeout: _autoLogout,
                      onReset: () => _remainingSeconds = _adminInactivityTimeout,
                    ),
                  ),
                ),
              IconButton(
                icon: const Icon(Icons.notifications),
                onPressed: () {
                  // 重置计时器
                  _resetInactivityTimer();
                  // 显示通知
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(content: Text('没有新通知')),
                  );
                },
              ),
            ],
          ),
          drawer: Drawer(
            child: ListView(
              padding: EdgeInsets.zero,
              children: [
                UserAccountsDrawerHeader(
                  accountName: Text(_currentUser.name),
                  accountEmail: Text(_currentUser.email ?? ''),
                  currentAccountPicture: CircleAvatar(
                    backgroundImage: _getAvatarImage(_currentUser.avatar),
                  ),
                  decoration: BoxDecoration(color: Colors.blue.shade800),
                ),
                ListTile(
                  leading: const Icon(Icons.home),
                  title: const Text('首页'),
                  selected: _selectedIndex == 0,
                  onTap: () {
                    _onItemTapped(0);
                    Navigator.pop(context);
                  },
                ),
                if (_isAdmin) ...[
                ListTile(
                  leading: const Icon(Icons.list_alt),
                  title: const Text('考试列表'),
                  selected: _selectedIndex == 1,
                  onTap: () {
                    _onItemTapped(1);
                    Navigator.pushNamed(context, '/exam_list');
                    Navigator.pop(context);
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.history),
                  title: const Text('历史记录'),
                  selected: _selectedIndex == 2,
                  onTap: () {
                    _onItemTapped(2);
                    Navigator.pop(context);
                    // TODO: 导航到历史记录页面
                  },
                ),
                ],
                const Divider(),
                if (_isAdmin) ...[
                ListTile(
                  leading: const Icon(Icons.settings),
                  title: const Text('设置'),
                  onTap: () {
                    Navigator.pop(context);
                    _showAdminSettingsDialog();
                  },
                ),
                ],
                ListTile(
                  leading: const Icon(Icons.logout),
                  title: const Text('退出登录'),
                  onTap: () {
                    Navigator.pop(context);
                    _logout();
                  },
                ),
                ListTile(
                  leading: const Icon(Icons.power_settings_new, color: Colors.red),
                  title: const Text('关闭APP', style: TextStyle(color: Colors.red)),
                  onTap: () {
                    _showCloseAppDialog();
                  },
                ),
              ],
            ),
          ),
          body: Stack(
            children: [
              _buildBody(),
              Positioned(
                top: 16,
                right: 16,
                child: Material(
                  color: Colors.transparent,
                  child: InkWell(
                    onTap: _showCloseAppDialog,
                    borderRadius: BorderRadius.circular(20),
                    child: Container(
                      padding: EdgeInsets.all(8),
                      decoration: BoxDecoration(
                        color: Colors.red.withOpacity(0.85),
                        shape: BoxShape.circle,
                        boxShadow: [
                          BoxShadow(
                            color: Colors.black26,
                            blurRadius: 6,
                            offset: Offset(0, 2),
                          ),
                        ],
                      ),
                      child: Icon(
                        Icons.power_settings_new,
                        color: Colors.white,
                        size: 24,
                      ),
                    ),
                  ),
                ),
              ),
            ],
          ),
          // 仅对管理员显示底部导航栏，学生用户只显示首页
          bottomNavigationBar: _isAdmin ? BottomNavigationBar(
            items: const <BottomNavigationBarItem>[
              BottomNavigationBarItem(
                icon: Icon(Icons.home),
                label: '首页',
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.list_alt),
                label: '考试',
              ),
              BottomNavigationBarItem(
                icon: Icon(Icons.account_circle),
                label: '我的',
              ),
            ],
            currentIndex: _selectedIndex,
            selectedItemColor: Colors.blue.shade800,
            onTap: _onItemTapped,
          ) : null,
        ),
      ),
    );
  }

  Widget _buildBody() {
    // 对于学生用户，总是显示首页
    if (!_isAdmin) {
      return _buildHomeTab();
    }
    
    // 对于管理员，根据所选标签显示不同内容
    switch (_selectedIndex) {
      case 0:
        return _buildHomeTab();
      case 1:
        return _buildExamTab();
      case 2:
        return _buildProfileTab();
      default:
        return _buildHomeTab();
    }
  }

  Widget _buildHomeTab() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    // 如果是管理员，显示考试历史记录
    if (_isAdmin) {
      return _buildAdminHomeView();
    }

    // 为普通用户显示考试信息
    return _buildStudentHomeView();
  }

  Widget _buildAdminHomeView() {
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16.0),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          // 未完成考试恢复按钮
          if (_hasIncompleteExams)
            Card(
              elevation: 3,
              color: Colors.red.shade50,
              shape: RoundedRectangleBorder(
                borderRadius: BorderRadius.circular(12),
                side: BorderSide(color: Colors.red.shade300, width: 1),
              ),
              child: Padding(
                padding: const EdgeInsets.all(16.0),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Row(
                      children: [
                        Icon(Icons.error_outline, color: Colors.red.shade800, size: 24),
                        SizedBox(width: 12),
                        Text(
                          '存在未完成的考试',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                            color: Colors.red.shade800,
                          ),
                        ),
                      ],
                    ),
                    SizedBox(height: 12),
                    Text(
                      '系统检测到未完成的考试状态，这可能由于设备故障、系统崩溃或异常退出导致。作为管理员，您可以恢复考试并调整剩余时间。',
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.red.shade900,
                      ),
                    ),
                    SizedBox(height: 16),
                    Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Text(
                          '共有 ${_incompleteExams.length} 个未完成的考试',
                          style: TextStyle(
                            fontWeight: FontWeight.bold,
                            color: Colors.red.shade800,
                          ),
                        ),
                        Spacer(),
                        ElevatedButton.icon(
                          onPressed: () => _showIncompleteExamsDialog(),
                          icon: Icon(Icons.restore, size: 18),
                          label: Text('管理未完成考试'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.red.shade800,
                            foregroundColor: Colors.white,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(8),
                            ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
            
          SizedBox(height: 16),
          
          // 欢迎消息
          Card(
            elevation: 4,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Row(
                children: [
                  CircleAvatar(
                    radius: 30,
                    backgroundImage: _getAvatarImage(_currentUser.avatar),
                    backgroundColor: Colors.blue.shade200,
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '欢迎, ${_currentUser.name}',
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 4),
                        const Text('管理员访问权限'),
                        const SizedBox(height: 4),
                        Container(
                          padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                          decoration: BoxDecoration(
                            color: Colors.green.shade100,
                            borderRadius: BorderRadius.circular(12),
                            border: Border.all(color: Colors.green.shade300),
                          ),
                          child: Text(
                            '管理员',
                            style: TextStyle(
                              color: Colors.green.shade800,
                              fontWeight: FontWeight.bold,
                              fontSize: 12,
                            ),
                          ),
                        ),
                        const SizedBox(height: 12),
                        Row(
                          children: [
                            Expanded(
                              child: ElevatedButton.icon(
                          icon: const Icon(Icons.download, size: 18),
                          label: const Text('加载试题/学生/须知'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                            foregroundColor: Colors.white,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20),
                            ),
                          ),
                          onPressed: _loadAllFromPath,
                              ),
                            ),
                            const SizedBox(width: 8),
                            ElevatedButton.icon(
                              icon: const Icon(Icons.settings, size: 18),
                              label: const Text('专用设备'),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.orange,
                                foregroundColor: Colors.white,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(20),
                                ),
                              ),
                              onPressed: _showDedicatedDeviceDialog,
                            ),
                          ],
                        ),
                        const SizedBox(height: 12),
                        Row(
                          children: [
                            Expanded(
                              child: ElevatedButton.icon(
                                icon: const Icon(Icons.delete_sweep, size: 18),
                                label: const Text('批量清除试卷'),
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: Colors.red,
                                  foregroundColor: Colors.white,
                                  shape: RoundedRectangleBorder(
                                    borderRadius: BorderRadius.circular(20),
                                  ),
                                ),
                                onPressed: _showBatchClearExamsDialog,
                              ),
                            ),
                            const SizedBox(width: 8),
                            ElevatedButton.icon(
                              icon: const Icon(Icons.info_outline, size: 18),
                              label: const Text('数据统计'),
                              style: ElevatedButton.styleFrom(
                                backgroundColor: Colors.teal,
                                foregroundColor: Colors.white,
                                shape: RoundedRectangleBorder(
                                  borderRadius: BorderRadius.circular(20),
                                ),
                              ),
                              onPressed: _showDataStatistics,
                            ),
                          ],
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
          ),
          const SizedBox(height: 24),
          
          // 设备上的考试记录
          const Text(
            '本设备考试历史记录',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 16),
          // 日志查看按钮
          Align(
            alignment: Alignment.centerRight,
            child: ElevatedButton.icon(
              icon: Icon(Icons.visibility, size: 18),
              label: Text('查看切后台日志'),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.deepOrange,
                foregroundColor: Colors.white,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(20),
                ),
              ),
              onPressed: () {
                Navigator.pushNamed(context, '/log_view');
              },
            ),
          ),
          const SizedBox(height: 16),
          // 显示所有考试的历史记录
          _buildExamHistoryList(),
        ],
      ),
    );
  }

  Widget _buildExamHistoryList() {
    if (_exams.isEmpty) {
      return Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.history, size: 64, color: Colors.grey.shade400),
            const SizedBox(height: 16),
            const Text(
              '暂无考试历史记录',
              style: TextStyle(fontSize: 18, color: Colors.grey),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: _exams.length,
      itemBuilder: (context, index) {
        final exam = _exams[index];
        return Card(
          margin: const EdgeInsets.only(bottom: 12),
          elevation: 2,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          child: InkWell(
            onTap: () => _viewExamResults(exam),
            borderRadius: BorderRadius.circular(12),
            child: Padding(
              padding: const EdgeInsets.all(16),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Row(
                    children: [
                      Container(
                        width: 40,
                        height: 40,
                        decoration: BoxDecoration(
                          color: Colors.blue.shade100,
                          borderRadius: BorderRadius.circular(8),
                        ),
                        child: Icon(
                          Icons.assignment,
                          color: Colors.blue.shade800,
                        ),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Column(
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [
                            Text(
                              exam.title,
                              style: const TextStyle(
                                fontSize: 16,
                                fontWeight: FontWeight.bold,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                            const SizedBox(height: 4),
                            Text(
                              exam.description,
                              style: TextStyle(
                                fontSize: 14,
                                color: Colors.grey.shade700,
                              ),
                              maxLines: 1,
                              overflow: TextOverflow.ellipsis,
                            ),
                          ],
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Flexible(
                        child: _buildInfoChip(Icons.question_answer, '${exam.questions.length}题', Colors.orange),
                      ),
                      Flexible(
                        child: _buildInfoChip(Icons.timer, '${exam.duration}分钟', Colors.green),
                      ),
                      Flexible(
                        child: _buildInfoChip(Icons.score, '${exam.totalScore}分', Colors.blue),
                      ),
                    ],
                  ),
                  const SizedBox(height: 12),
                  Align(
                    alignment: Alignment.centerRight,
                    child: ElevatedButton.icon(
                      onPressed: () => _viewExamResults(exam),
                      icon: const Icon(Icons.bar_chart, size: 16),
                      label: const Text('查看考试结果'),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.blue.shade700,
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                        shape: RoundedRectangleBorder(
                          borderRadius: BorderRadius.circular(8),
                        ),
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
        );
      },
    );
  }

  void _viewExamResults(Exam exam) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => StudentResultsScreen(exam: exam),
        settings: RouteSettings(name: 'StudentResultsScreen'),
      ),
    );
  }

  Widget _buildStudentHomeView() {
    if (_isLoading) {
      return const Center(child: CircularProgressIndicator());
    }

    // 为普通用户显示考试信息
    return SingleChildScrollView(
      padding: const EdgeInsets.all(16.0),
        child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
          children: [
          // 未完成考试恢复按钮 - 移到最顶部并增加显眼程度
          if (_hasIncompleteExams)
            Container(
              margin: EdgeInsets.only(bottom: 20.0),
              width: double.infinity,
              child: Card(
                elevation: 5,
                color: Colors.red.shade50,
                shape: RoundedRectangleBorder(
                  borderRadius: BorderRadius.circular(12),
                  side: BorderSide(color: Colors.red.shade300, width: 2),
                ),
                child: Padding(
                  padding: const EdgeInsets.all(16.0),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Icon(Icons.error_outline, color: Colors.red.shade800, size: 32),
                          SizedBox(width: 12),
                          Expanded(
                            child: Text(
                              '紧急提示：检测到未完成的考试',
                              style: TextStyle(
                                fontSize: 20,
                                fontWeight: FontWeight.bold,
                                color: Colors.red.shade800,
                              ),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 16),
                      Text(
                        '系统检测到您有未完成的考试，可能由于意外退出或设备故障导致。您可以恢复之前的考试继续作答，无需重新开始。',
                        style: TextStyle(
                          fontSize: 16,
                          color: Colors.red.shade900,
                        ),
            ),
                      SizedBox(height: 20),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
            ElevatedButton.icon(
                            onPressed: () => _showIncompleteExamsDialog(),
                            icon: Icon(Icons.restore, size: 24),
                            label: Text(
                              '立即恢复考试',
                              style: TextStyle(
                                fontSize: 18,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
              style: ElevatedButton.styleFrom(
                              backgroundColor: Colors.red.shade700,
                foregroundColor: Colors.white,
                              padding: EdgeInsets.symmetric(horizontal: 20, vertical: 12),
                              shape: RoundedRectangleBorder(
                                borderRadius: BorderRadius.circular(10),
                              ),
              ),
            ),
          ],
        ),
                    ],
                  ),
                ),
              ),
            ),
          
          // 欢迎消息卡片
          Card(
            elevation: 4,
            shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(16),
            ),
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Column(
                children: [
                  Row(
                children: [
                  CircleAvatar(
                    radius: 30,
                    backgroundImage: _getAvatarImage(_currentUser.avatar),
                  ),
                  const SizedBox(width: 16),
                  Expanded(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '欢迎, ${_currentUser.name}',
                          style: const TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        const SizedBox(height: 4),
                        Text(
                          _currentUser is Student 
                            ? (((_currentUser as Student).assignedExamId?.isNotEmpty ?? false) 
                                ? '已为您分配了专属考试' 
                                : '暂未分配考试')
                            : '共有 ${_exams.length} 个考试可参加'
                        ),
                      ],
                    ),
                  ),
                ],
              ),
                  const SizedBox(height: 16),
                  // 学生操作按钮行
                  Row(
                    children: [
                      Expanded(
                        child: ElevatedButton.icon(
                          icon: const Icon(Icons.settings, size: 18),
                          label: const Text('专用设备'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.orange,
                            foregroundColor: Colors.white,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20),
                            ),
                          ),
                          onPressed: _showDedicatedDeviceDialog,
                        ),
                      ),
                      const SizedBox(width: 12),
                      Expanded(
                        child: ElevatedButton.icon(
                          icon: const Icon(Icons.logout, size: 18),
                          label: const Text('退出登录'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.red,
                            foregroundColor: Colors.white,
                            shape: RoundedRectangleBorder(
                              borderRadius: BorderRadius.circular(20),
                            ),
                          ),
                          onPressed: _logout,
                        ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
          ),
          
          const SizedBox(height: 24),
          
          // 未开始的考试
          const Text(
            '待参加考试',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          
          // 构建未开始的考试列表
          FutureBuilder<List<Exam>>(
            future: _getExamsByStatus(ExamStatus.notStarted),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Center(child: CircularProgressIndicator());
              }
              
              final pendingExams = snapshot.data ?? [];
              
              if (pendingExams.isEmpty) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 16.0),
                  child: Center(
                    child: Text(
                      '没有待参加的考试',
                      style: TextStyle(color: Colors.grey.shade600),
                    ),
                  ),
                );
              }
              
              return ListView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: pendingExams.length,
                itemBuilder: (context, index) {
                  final exam = pendingExams[index];
                  return _buildRealExamCard(
                    exam: exam,
                    status: ExamStatus.notStarted,
                    onTap: () => _navigateToExam(exam),
                  );
                },
              );
            },
          ),
          
          const SizedBox(height: 24),
          
          // 已完成的考试
          const Text(
            '已完成考试',
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
            ),
          ),
          const SizedBox(height: 8),
          
          // 构建已完成的考试列表
          FutureBuilder<List<Exam>>(
            future: _getExamsByStatus(ExamStatus.completed),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const Center(child: CircularProgressIndicator());
              }
              
              final completedExams = snapshot.data ?? [];
              
              if (completedExams.isEmpty) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 16.0),
                  child: Center(
                    child: Text(
                      '没有已完成的考试',
                      style: TextStyle(color: Colors.grey.shade600),
                    ),
                  ),
                );
              }
              
              return ListView.builder(
                shrinkWrap: true,
                physics: const NeverScrollableScrollPhysics(),
                itemCount: completedExams.length,
                itemBuilder: (context, index) {
                  final exam = completedExams[index];
                  return FutureBuilder<ExamResult?>(
                    future: ExamStateService.getCurrentUserExamResult(exam.id),
                    builder: (context, resultSnapshot) {
                      final result = resultSnapshot.data;
                      return _buildRealExamCard(
                        exam: exam,
                        status: ExamStatus.completed,
                        result: result,
                        onTap: () => _showCompletedExamDialog(exam),
                      );
                    },
                  );
                },
              );
            },
          ),
        ],
      ),
    );
  }

  // 根据状态获取考试列表
  Future<List<Exam>> _getExamsByStatus(ExamStatus targetStatus) async {
    List<Exam> filteredExams = [];
    final currentUser = UserData.currentUser;
    if (currentUser == null) return [];
    
    // 如果是学生用户，只显示分配给该学生的考试
    List<Exam> availableExams = [];
    if (currentUser is Student) {
      // 获取学生分配的考试ID
      final assignedExamId = currentUser.assignedExamId;
      if (assignedExamId != null && assignedExamId.isNotEmpty) {
        // 只查找分配给该学生的考试
                 final assignedExam = _exams.firstWhere(
           (exam) => exam.id == assignedExamId,
           orElse: () => Exam(
             id: '',
             title: '',
             description: '',
             duration: 0,
             questions: [],
             totalScore: 0,
           ),
         );
        if (assignedExam.id.isNotEmpty) {
          availableExams = [assignedExam];
        }
      }
    } else {
      // 管理员用户显示所有考试
      availableExams = _exams;
    }
    
    for (var exam in availableExams) {
      final status = await ExamStateService.getExamStatus(exam.id, userId: currentUser.id);
      if (status == targetStatus) {
        filteredExams.add(exam);
      }
    }
    
    return filteredExams;
  }

  // 构建实际的考试卡片
  Widget _buildRealExamCard({
    required Exam exam,
    required ExamStatus status,
    ExamResult? result,
    required VoidCallback onTap,
  }) {
    Color cardColor;
    IconData cardIcon;
    
    switch (status) {
      case ExamStatus.notStarted:
        cardColor = Colors.blue.shade800;
        cardIcon = Icons.assignment;
        break;
      case ExamStatus.inProgress:
        cardColor = Colors.orange.shade800;
        cardIcon = Icons.assignment_turned_in;
        break;
      case ExamStatus.completed:
        cardColor = Colors.green.shade800;
        cardIcon = Icons.assignment_turned_in;
        break;
    }
    
    return Card(
      margin: const EdgeInsets.only(bottom: 12),
      elevation: 3,
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.circular(12),
      ),
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(16.0),
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: cardColor.withOpacity(0.1),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Icon(
                  cardIcon,
                  color: cardColor,
                  size: 30,
                ),
              ),
              const SizedBox(width: 16),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      exam.title,
                      style: const TextStyle(
                        fontSize: 16,
                        fontWeight: FontWeight.bold,
                      ),
                      maxLines: 1,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 4),
                    Text(
                      exam.description,
                      style: TextStyle(
                        fontSize: 14,
                        color: Colors.grey.shade600,
                      ),
                      maxLines: 2,
                      overflow: TextOverflow.ellipsis,
                    ),
                    const SizedBox(height: 8),
                    Row(
                      children: [
                        Flexible(
                          child: _buildInfoChip(
                            Icons.timer,
                            '${exam.duration}分钟',
                            Colors.blue.shade700,
                          ),
                        ),
                        const SizedBox(width: 8),
                        Flexible(
                          child: _buildInfoChip(
                            Icons.help_outline,
                            '${exam.questions.length}题',
                            Colors.orange.shade700,
                          ),
                        ),
                        const SizedBox(width: 8),
                        Flexible(
                          child: _buildInfoChip(
                            Icons.score,
                            '${exam.totalScore}分',
                            Colors.purple.shade700,
                          ),
                        ),
                      ],
                    ),
                    if (status == ExamStatus.completed && result != null)
                      Padding(
                        padding: const EdgeInsets.only(top: 8.0),
                        child: Row(
                          children: [
                            Container(
                              padding: const EdgeInsets.symmetric(
                                horizontal: 8, 
                                vertical: 4,
                              ),
                              decoration: BoxDecoration(
                                color: result.totalScore >= (exam.totalScore * 0.6)
                                  ? Colors.green.shade100 
                                  : Colors.red.shade100,
                                borderRadius: BorderRadius.circular(12),
                                border: Border.all(
                                  color: result.totalScore >= (exam.totalScore * 0.6) 
                                    ? Colors.green.shade400 
                                    : Colors.red.shade400,
                                ),
                              ),
                              child: Text(
                                '得分: ${result.totalScore}/${exam.totalScore}',
                                style: TextStyle(
                                  fontSize: 12,
                                  fontWeight: FontWeight.bold,
                                  color: result.totalScore >= (exam.totalScore * 0.6) 
                                    ? Colors.green.shade700 
                                    : Colors.red.shade700,
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                  ],
                ),
              ),
              Icon(
                Icons.chevron_right,
                color: Colors.grey.shade400,
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 构建信息小标签
  Widget _buildInfoChip(IconData icon, String label, Color color) {
    return SizedBox(
      width: 25, // 强制固定宽度
      child: Container(
        padding: const EdgeInsets.symmetric(horizontal: 3, vertical: 1),
        decoration: BoxDecoration(
          color: color.withOpacity(0.1),
          borderRadius: BorderRadius.circular(6),
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(icon, size: 8, color: color), // 进一步减少图标大小
            const SizedBox(width: 1), // 进一步减少间距
            Expanded( // 使用Expanded而不是Flexible
              child: Text(
                label,
                style: TextStyle(
                  fontSize: 8, // 进一步减少字体大小
                  color: color,
                  fontWeight: FontWeight.w500,
                ),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
              ),
            ),
          ],
        ),
      ),
    );
  }

  // 导航到考试
  void _navigateToExam(Exam exam) {
    Navigator.push(
      context,
      MaterialPageRoute(
        builder: (context) => ExamRulesScreen(exam: exam),
        settings: RouteSettings(name: 'ExamRulesScreen'),
      ),
    ).then((_) {
      // 只有在用户返回到首页时才刷新考试列表
      // 如果用户进入了考试，这个回调不会被触发
      _loadExams();
    });
  }

  // 显示已完成考试的对话框
  void _showCompletedExamDialog(Exam exam) async {
    // 获取考试结果
    final result = await ExamStateService.getCurrentUserExamResult(exam.id);
    
    if (!mounted) return;
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('考试已完成'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text('您已完成此考试，不能重复参加'),
            if (result != null) ...[
              const SizedBox(height: 16),
              _buildResultSummary(result, exam.totalScore),
            ],
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: const Text('返回'),
          ),
          if (result != null)
            ElevatedButton(
              onPressed: () {
                Navigator.pop(context);
                Navigator.push(
                  context,
                  MaterialPageRoute(
                    builder: (context) => ResultScreen(
                      exam: exam,
                      result: result,
                    ),
                    settings: RouteSettings(name: 'ResultScreen'),
                  ),
                );
              },
              child: const Text('查看详情'),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.blue,
                foregroundColor: Colors.white,
              ),
            ),
        ],
      ),
    );
  }
  
  // 构建成绩摘要
  Widget _buildResultSummary(ExamResult result, int totalExamScore) {
    final scorePercentage = (result.totalScore / totalExamScore * 100).toStringAsFixed(1);
    final bool passed = result.totalScore >= (totalExamScore * 0.6);
    
    return Container(
      padding: const EdgeInsets.all(16),
      decoration: BoxDecoration(
        color: passed ? Colors.green.shade50 : Colors.red.shade50,
        borderRadius: BorderRadius.circular(8),
        border: Border.all(color: passed ? Colors.green.shade200 : Colors.red.shade200),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            children: [
              Icon(
                passed ? Icons.check_circle : Icons.cancel,
                color: passed ? Colors.green : Colors.red,
                size: 24,
              ),
              const SizedBox(width: 8),
              Text(
                passed ? '通过' : '未通过',
                style: TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: passed ? Colors.green : Colors.red,
                ),
              ),
            ],
          ),
          const SizedBox(height: 8),
          Text(
            '总分: ${result.totalScore}/${totalExamScore}',
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ),
          Text(
            '得分率: $scorePercentage%',
            style: const TextStyle(
              fontSize: 16,
              fontWeight: FontWeight.w500,
            ),
          ),
          if (!result.isGraded)
            Padding(
              padding: const EdgeInsets.only(top: 8),
              child: Text(
                '* 主观题尚未评分完成',
                style: TextStyle(
                  fontSize: 14,
                  fontStyle: FontStyle.italic,
                  color: Colors.orange,
                ),
              ),
            ),
        ],
      ),
    );
  }

  Widget _buildExamTab() {
    // 简单重定向到考试列表页面
    WidgetsBinding.instance.addPostFrameCallback((_) {
      Navigator.pushReplacementNamed(context, '/exam_list');
    });
    
    return const Center(
      child: CircularProgressIndicator(),
    );
  }

  Widget _buildProfileTab() {
    return ListView(
      padding: const EdgeInsets.all(16.0),
      children: [
        // 用户信息卡
        Card(
          elevation: 4,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          child: Padding(
            padding: const EdgeInsets.all(16.0),
            child: Column(
              children: [
                CircleAvatar(
                  radius: 50,
                  backgroundImage: _getAvatarImage(_currentUser.avatar),
                  backgroundColor: Colors.blue.shade200,
                ),
                const SizedBox(height: 16),
                Text(
                  _currentUser.name,
                  style: const TextStyle(
                    fontSize: 24,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 8),
                Text(
                  _currentUser.email ?? '',
                  style: TextStyle(
                    fontSize: 16,
                    color: Colors.grey.shade600,
                  ),
                ),
                if (_isAdmin) ...[
                  const SizedBox(height: 8),
                  Container(
                    padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                    decoration: BoxDecoration(
                      color: Colors.green.shade100,
                      borderRadius: BorderRadius.circular(16),
                      border: Border.all(color: Colors.green.shade300),
                    ),
                    child: Text(
                      '管理员',
                      style: TextStyle(
                        color: Colors.green.shade800,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ),
                ],
                const SizedBox(height: 16),
                const Divider(),
                // 如果不是管理员，不显示考试统计信息
                // 如果是管理员显示管理员特有功能
                if (_isAdmin) ...[

                  ListTile(
                    leading: Icon(Icons.assignment, color: Colors.blue.shade700),
                    title: Text('考试管理', style: TextStyle(color: Colors.blue.shade700)),
                    trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                    onTap: () {
                      // 导航到考试管理页面
                      Navigator.pushReplacementNamed(context, '/exam_list');
                    },
                  ),
                  ListTile(
                    leading: Icon(Icons.quiz, color: Colors.purple.shade700),
                    title: Text('试题管理', style: TextStyle(color: Colors.purple.shade700)),
                    subtitle: Text('查看和管理设备上的试题'),
                    trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                    onTap: () {
                      _showExamManagementDialog();
                    },
                  ),
                  ListTile(
                    leading: Icon(Icons.delete_sweep, color: Colors.red.shade700),
                    title: Text('删除考试记录', style: TextStyle(color: Colors.red.shade700)),
                    subtitle: Text('删除学生的答题记录，允许重新答题'),
                    trailing: const Icon(Icons.arrow_forward_ios, size: 16),
                    onTap: () {
                      _showDeleteExamRecordsDialog();
                    },
                  ),
                ],
              ],
            ),
          ),
        ),
        const SizedBox(height: 16),
        
        // 设置列表
        Card(
          elevation: 4,
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(16),
          ),
          child: Column(
            children: [
              if (_isAdmin || debugMode) ...[
                const Divider(height: 1),
                ListTile(
                  leading: const Icon(Icons.refresh, color: Colors.orange),
                  title: const Text('重置所有考试状态', style: TextStyle(color: Colors.orange)),
                  subtitle: const Text('开发调试用', style: TextStyle(fontSize: 12)),
                  onTap: () {
                    _showResetExamStatesDialog();
                  },
                ),
              ],
              const Divider(height: 1),
              ListTile(
                leading: const Icon(Icons.logout, color: Colors.red),
                title: const Text('退出登录', style: TextStyle(color: Colors.red)),
                onTap: () {
                  _logout();
                },
              ),
            ],
          ),
        ),
      ],
    );
  }

  // 显示重置考试状态的确认对话框
  void _showResetExamStatesDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('重置所有考试状态'),
        content: const Text(
          '这将清除所有考试的状态和结果，您将能够重新参加所有考试。\n\n此操作不可恢复，确定要继续吗？',
          style: TextStyle(height: 1.5),
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              _resetAllExamStates();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: const Text('确认重置'),
          ),
        ],
      ),
    );
  }
  
  // 重置所有考试状态
  Future<void> _resetAllExamStates() async {
    setState(() {
      _isLoading = true;
    });
    
    try {
      // 获取所有考试
      for (var exam in _exams) {
        // 清除用户相关的考试状态和结果
        final currentUser = UserData.currentUser;
        if (currentUser != null) {
          await ExamStateService.removeExamState(exam.id, currentUser.id);
          // 尝试找出并清除考试结果
          // 由于没有直接的removeExamResult方法，我们使用SharedPreferences直接操作
          final prefs = await SharedPreferences.getInstance();
          final resultKey = 'exam_result_${exam.id}_${currentUser.id}';
          await prefs.remove(resultKey);
        }
      }
      
      // 重新加载考试
      await _loadExams();
      
      // 显示成功消息
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('所有考试状态已重置，现在可以重新参加所有考试'),
          backgroundColor: Colors.green,
          duration: Duration(seconds: 3),
        ),
      );
    } catch (e) {
      debugPrint('重置考试状态失败: $e');
      // 显示错误消息
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('重置考试状态失败: $e'),
          backgroundColor: Colors.red,
          duration: Duration(seconds: 3),
        ),
      );
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  Future<void> _loadAllFromPath() async {
    // 检查是否启用了专用设备模式
    final isDedicated = await DeviceConfigService.isDedicatedDevice();
    
    if (isDedicated) {
      // 如果是专用设备模式，直接调用专用设备加载方法
      _loadFromDedicatedPath();
      return;
    }
    
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const AlertDialog(
        content: Row(
          children: [
            CircularProgressIndicator(),
            SizedBox(width: 20),
            Text('正在自动加载目录下的Excel文件...'),
          ],
        ),
      ),
    );
    String msg = '';
    bool success = true;
    List<String> details = [];
    try {
      // 1. 获取Excel目录
      String? dirPath;
      if (Platform.isAndroid) {
        // 获取包名
        final packageName = (await MethodChannel('plugins.flutter.io/package_info').invokeMethod<String>('getPackageName')) ?? '';
        dirPath = '/storage/emulated/0/Android/data/$packageName/files';
      } else {
        final directory = await getApplicationDocumentsDirectory();
        dirPath = '${directory.path}/ExamApp';
      }
      final dir = Directory(dirPath);
      if (!await dir.exists()) {
        await dir.create(recursive: true);
      }
      // 2. 只识别固定文件名（支持xlsx和xls格式）
      final Map<String, String> fileMap = {
        '学生信息.xlsx': 'student',
        '学生信息.xls': 'student',
        '试题信息.xlsx': 'exam',
        '试题信息.xls': 'exam',
        '考试须知.xlsx': 'notice',
        '考试须知.xls': 'notice',
      };
      final files = dir
          .listSync()
          .whereType<File>()
          .where((f) => fileMap.keys.contains(f.path.split('/').last))
          .toList();
      if (files.isEmpty) {
        msg = '未在$dirPath目录下找到指定名称的Excel文件（学生信息.xlsx、试题信息.xlsx、考试须知.xlsx）';
        success = false;
      } else {
        int studentCount = 0, examCount = 0, noticeCount = 0;
        for (final file in files) {
          final filename = file.path.split('/').last;
          final type = fileMap[filename];
          if (type == 'student') {
            final result = await StudentService.importFromExcel(file);
            details.add('学生信息: $filename => ${result.message}');
            if (result.success) studentCount++;
          } else if (type == 'exam') {
            final exam = await ExamService.createExamFromExcelFile(file);
            details.add('试题: $filename => ${exam != null ? '导入成功' : '导入失败'}');
            if (exam != null) examCount++;
          } else if (type == 'notice') {
            details.add('须知: $filename => 暂不支持自动导入');
            // if (await NoticeService.importFromExcel(file)) noticeCount++;
          }
        }
        msg = '学生信息导入: $studentCount 个文件\n试题导入: $examCount 个文件\n须知导入: $noticeCount 个文件';
      }
    } catch (e) {
      msg = '加载失败: $e';
      success = false;
    }
    if (mounted) {
      Navigator.of(context).pop();
      showDialog(
        context: context,
        builder: (context) => AlertDialog(
          title: Text(success ? '加载完成' : '加载失败'),
          content: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(msg),
                if (details.isNotEmpty) ...[
                  const SizedBox(height: 12),
                  ...details.map((d) => Text(d)),
                ]
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('确定'),
            ),
          ],
        ),
      );
    }
    // 重新加载考试数据
    _loadExams();
  }

  void _showCloseAppDialog() {
    final TextEditingController closeAppPasswordController = TextEditingController();
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('关闭APP'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            const Text('请输入密码以关闭APP'),
            const SizedBox(height: 16),
            TextField(
              controller: closeAppPasswordController,
              obscureText: true,
              decoration: const InputDecoration(
                labelText: '密码',
                border: OutlineInputBorder(),
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
              closeAppPasswordController.dispose();
            },
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              final password = closeAppPasswordController.text.trim();
              // 使用统一的管理员密码验证
              if (UserData.verifyAdminPassword(password)) {
                Navigator.pop(context);
                closeAppPasswordController.dispose();
                await Future.delayed(const Duration(milliseconds: 200));
                SystemNavigator.pop(); // 关闭APP
              } else {
                ScaffoldMessenger.of(context).showSnackBar(
                  const SnackBar(content: Text('密码错误，无法关闭APP'), backgroundColor: Colors.red),
                );
              }
            },
            child: const Text('确认关闭'),
          ),
        ],
      ),
    ).then((_) {
      // 确保对话框关闭后释放控制器
      closeAppPasswordController.dispose();
    });
  }

  // 检查未完成的考试
  Future<void> _checkIncompleteExams() async {
    // 防止短时间内重复检查（避免从考试页面返回时立即重复检查）
    final now = DateTime.now();
    if (_lastCheckTime != null && now.difference(_lastCheckTime!).inSeconds < 5) {
      AppLogger.log('⏰ 距离上次检查不足5秒，跳过本次检查');
      AppLogger.log('   上次检查: $_lastCheckTime');
      AppLogger.log('   本次检查: $now');
      AppLogger.log('   时间差: ${now.difference(_lastCheckTime!).inSeconds}秒');
      return;
    }

    _lastCheckTime = now;

    if (mounted) {
      // 显示加载指示器
      setState(() {
        _isLoading = true;
      });
    }

    try {
      final currentUser = UserData.currentUser;
      AppLogger.log('=== 开始检查未完成考试 ===');
      AppLogger.log('检查触发时间: ${DateTime.now()}');
      AppLogger.log('当前用户: ${currentUser?.id} (${currentUser?.name})');
      AppLogger.log('用户类型: ${_isAdmin ? "管理员" : "学生"}');
      AppLogger.log('检查原因: 可能是页面初始化、从考试页面返回或其他触发');

      final incompleteExams = await ExamStateService.getIncompleteExams();

      if (!mounted) return;

      setState(() {
        _incompleteExams = incompleteExams;
        _hasIncompleteExams = incompleteExams.isNotEmpty;
        _isLoading = false;
      });

      AppLogger.log('未完成考试检查完成，找到 ${incompleteExams.length} 个');
      for (var exam in incompleteExams) {
        AppLogger.log('未完成考试: ${exam['examTitle']} (ID: ${exam['examId']})');
        AppLogger.log('  - 剩余时间: ${exam['remainingSeconds']}秒');
        AppLogger.log('  - 最后更新: ${exam['lastUpdated']}');
        AppLogger.log('  - 已答题数: ${exam['answerCount']}/${exam['totalQuestions']}');
      }

      // 如果有未完成的考试，显示恢复提示
      if (_hasIncompleteExams) {
        // 避免在build过程中显示对话框
        WidgetsBinding.instance.addPostFrameCallback((_) {
          // 确保界面已完全构建
          if (mounted) {
            AppLogger.log('✅ 准备显示未完成考试对话框');
            _showIncompleteExamsDialog();
          }
        });
      } else {
        AppLogger.log('❌ 没有找到未完成的考试');

        // 如果没有找到未完成考试，但用户是学生，我们手动检查一下
        if (!_isAdmin) {
          AppLogger.log('🔍 学生用户没有找到未完成考试，进行手动检查...');
          _debugCheckExamStatesForCurrentUser();
        }
      }
    } catch (e) {
      debugPrint('检查未完成考试出错: $e');
      if (mounted) {
        setState(() {
          _isLoading = false;
        });
      }
    }
  }
  
  // 显示未完成考试对话框
  void _showIncompleteExamsDialog() {
    AppLogger.log('🔍 显示未完成考试对话框');
    AppLogger.log('当前用户是否为管理员: $_isAdmin');
    AppLogger.log('当前用户信息: ${UserData.currentUser?.name} (${UserData.currentUser?.id})');
    AppLogger.log('未完成考试数量: ${_incompleteExams.length}');

    // 直接检查用户ID是否为管理员，而不依赖_isAdmin标志
    final currentUser = UserData.currentUser;
    final isActuallyAdmin = (currentUser?.id == 'admin001' || currentUser?.id == 'admin');

    AppLogger.log('实际管理员检查: $isActuallyAdmin');
    AppLogger.log('用户ID: ${currentUser?.id}');

    if (!isActuallyAdmin) {
      // 学生用户看到的简化版本
      if (_incompleteExams.isEmpty) {
        return;
      }
      
      // 取第一个未完成的考试（通常学生只会有一个）
      final exam = _incompleteExams.first;
      
      // 创建密码控制器
      final TextEditingController passwordController = TextEditingController();
      bool isPasswordVisible = false;

      showDialog(
        context: context,
        barrierDismissible: false, // 阻止用户点击外部关闭
        builder: (context) => StatefulBuilder(
          builder: (context, setState) => SingleChildScrollView(
            child: AlertDialog(
              title: Row(
                children: [
                  Icon(Icons.warning_amber, color: Colors.red, size: 24),
                  SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      '发现未完成的考试',
                      style: TextStyle(
                        color: Colors.red.shade700,
                        fontSize: 16,
                      ),
                    ),
                  ),
                ],
              ),
              content: Container(
                width: double.maxFinite,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '您有一个未完成的考试需要恢复：',
                      style: TextStyle(fontWeight: FontWeight.bold, fontSize: 14),
                    ),
                    SizedBox(height: 12),
                    // 考试信息卡片
                    Container(
                      padding: EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Colors.blue.shade50,
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: Colors.blue.shade200),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            exam['examTitle'],
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                              color: Colors.blue.shade800,
                            ),
                          ),
                          SizedBox(height: 8),
                          _buildInfoRow('剩余时间', _formatTime(exam['remainingSeconds'])),
                          SizedBox(height: 4),
                          _buildInfoRow('已答题数', '${exam['answerCount']}/${exam['totalQuestions']}'),
                          SizedBox(height: 4),
                          _buildInfoRow('最后保存', _formatDateTime(DateTime.parse(exam['lastUpdated']))),
                        ],
                      ),
                    ),
                    SizedBox(height: 16),
                    // 管理员密码验证区域
                    Container(
                      padding: EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Colors.orange.shade50,
                        borderRadius: BorderRadius.circular(8),
                        border: Border.all(color: Colors.orange.shade200),
                      ),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Row(
                            children: [
                              Icon(Icons.security, color: Colors.orange.shade700, size: 18),
                              SizedBox(width: 6),
                              Text(
                                '需要管理员密码验证',
                                style: TextStyle(
                                  fontWeight: FontWeight.bold,
                                  color: Colors.orange.shade700,
                                  fontSize: 13,
                                ),
                              ),
                            ],
                          ),
                          SizedBox(height: 8),
                          Text(
                            '恢复考试需要管理员授权，请输入管理员密码：',
                            style: TextStyle(
                              fontSize: 12,
                              color: Colors.grey.shade700,
                            ),
                          ),
                          SizedBox(height: 10),
                          TextField(
                            controller: passwordController,
                            obscureText: !isPasswordVisible,
                            decoration: InputDecoration(
                              labelText: '管理员密码',
                              hintText: '请输入管理员密码',
                              prefixIcon: Icon(Icons.lock, size: 18),
                              suffixIcon: IconButton(
                                icon: Icon(
                                  isPasswordVisible ? Icons.visibility : Icons.visibility_off,
                                  size: 18,
                                ),
                                onPressed: () {
                                  setState(() {
                                    isPasswordVisible = !isPasswordVisible;
                                  });
                                },
                              ),
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(6),
                              ),
                              contentPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
                              isDense: true,
                            ),
                            style: TextStyle(fontSize: 13),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    passwordController.dispose();
                    Navigator.pop(context);
                  },
                  style: TextButton.styleFrom(
                    padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  ),
                  child: Text('稍后再说', style: TextStyle(fontSize: 13)),
                ),
                ElevatedButton.icon(
                  icon: Icon(Icons.play_arrow, size: 16),
                  label: Text('恢复考试', style: TextStyle(fontSize: 13)),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue,
                    foregroundColor: Colors.white,
                    padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                  ),
                  onPressed: () {
                    final password = passwordController.text.trim();

                    if (password.isEmpty) {
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('请输入管理员密码'),
                          backgroundColor: Colors.orange,
                        ),
                      );
                      return;
                    }

                    if (UserData.verifyAdminPassword(password)) {
                      // 密码验证成功
                      AppLogger.log('✅ 管理员密码验证成功，准备恢复考试');

                      // 关闭对话框
                      passwordController.dispose();
                      Navigator.pop(context);

                      // 显示成功提示
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('管理员密码验证成功，正在恢复考试...'),
                          backgroundColor: Colors.green,
                          duration: Duration(seconds: 1),
                        ),
                      );

                      // 使用简单的延迟执行恢复操作，避免构建作用域冲突
                      Future.delayed(Duration(milliseconds: 800), () {
                        if (mounted) {
                          _resumeExamForStudent(exam);
                        }
                      });
                    } else {
                      // 密码错误
                      AppLogger.log('❌ 管理员密码验证失败');
                      ScaffoldMessenger.of(context).showSnackBar(
                        SnackBar(
                          content: Text('管理员密码错误，请重试'),
                          backgroundColor: Colors.red,
                        ),
                      );
                    }
                  },
                ),
              ],
              actionsPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
            ),
          ),
        ),
      ).then((_) {
        // 确保对话框关闭时释放控制器
        try {
          passwordController.dispose();
        } catch (e) {
          // 忽略重复释放的错误
        }
      });
      return;
    }
    
    // 管理员版本
    showDialog(
      context: context,
      barrierDismissible: false, // 阻止用户点击外部关闭
      builder: (context) => AlertDialog(
        title: Text('发现未完成的考试'),
        content: Container(
          width: double.maxFinite,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('系统检测到您有未完成的考试，是否要恢复？'),
              SizedBox(height: 16),
              if (_incompleteExams.isNotEmpty)
                Container(
                  height: 200,
                  child: ListView.builder(
                    itemCount: _incompleteExams.length,
                    itemBuilder: (context, index) {
                      final exam = _incompleteExams[index];
                      final DateTime lastUpdated = DateTime.parse(exam['lastUpdated']);
                      final String formattedDate = DateFormat('yyyy-MM-dd HH:mm:ss').format(lastUpdated);
                      
                      return Card(
                        margin: EdgeInsets.only(bottom: 8),
                        child: ListTile(
                          title: Text(exam['examTitle']),
                          subtitle: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('剩余时间: ${_formatTime(exam['remainingSeconds'])}'),
                              Text('最后保存: $formattedDate'),
                              Text('已答题数: ${exam['answerCount']}/${exam['totalQuestions']}'),
                            ],
                          ),
                          trailing: ElevatedButton(
                            onPressed: () {
                              Navigator.pop(context); // 关闭对话框
                              _showAdminPasswordDialog(exam);
                            },
                            child: Text('恢复'),
                          ),
                        ),
                      );
                    },
                  ),
                ),
            ],
          ),
        ),
        actions: [], // 移除"稍后再说"按钮
      ),
    );
  }
  
  // 构建信息行
  Widget _buildInfoRow(String label, String value) {
    return Row(
      children: [
        Text(
          '$label: ',
          style: TextStyle(
            fontWeight: FontWeight.bold,
            color: Colors.grey.shade700,
          ),
        ),
        Text(
          value,
          style: TextStyle(
            color: Colors.black87,
          ),
        ),
      ],
    );
  }
  
  // 格式化日期时间
  String _formatDateTime(DateTime dateTime) {
    return DateFormat('yyyy-MM-dd HH:mm:ss').format(dateTime);
  }
  
  // 显示试题管理对话框
  void _showExamManagementDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.quiz, color: Colors.purple.shade700),
            SizedBox(width: 8),
            Text('试题管理'),
          ],
        ),
        content: Container(
          width: double.maxFinite,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 试题统计信息
              Card(
                color: Colors.purple.shade50,
                child: Padding(
                  padding: EdgeInsets.all(16),
                  child: Column(
                    children: [
                      Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Text(
                            '设备试题总数',
                            style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.bold,
                            ),
                          ),
                          Container(
                            padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                            decoration: BoxDecoration(
                              color: Colors.purple.shade100,
                              borderRadius: BorderRadius.circular(16),
                            ),
                            child: Text(
                              '${_exams.length} 套',
                              style: TextStyle(
                                color: Colors.purple.shade800,
                                fontWeight: FontWeight.bold,
                                fontSize: 18,
                              ),
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 8),
                      if (_exams.isNotEmpty) ...[
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text('总题目数'),
                            Text('${_getTotalQuestions()} 题'),
                          ],
                        ),
                        SizedBox(height: 4),
                        Row(
                          mainAxisAlignment: MainAxisAlignment.spaceBetween,
                          children: [
                            Text('平均时长'),
                            Text('${_getAverageDuration()} 分钟'),
                          ],
                        ),
                      ],
                    ],
                  ),
                ),
              ),
              SizedBox(height: 16),
              // 试题列表
              if (_exams.isEmpty)
                Padding(
                  padding: EdgeInsets.all(20),
                  child: Column(
                    children: [
                      Icon(Icons.quiz_outlined, size: 48, color: Colors.grey),
                      SizedBox(height: 8),
                      Text(
                        '暂无试题',
                        style: TextStyle(color: Colors.grey, fontSize: 16),
                      ),
                    ],
                  ),
                )
              else
                Container(
                  height: 300,
                  child: ListView.builder(
                    shrinkWrap: true,
                    itemCount: _exams.length,
                    itemBuilder: (context, index) {
                      final exam = _exams[index];
                      return Card(
                        margin: EdgeInsets.only(bottom: 8),
                        child: ListTile(
                          leading: CircleAvatar(
                            backgroundColor: Colors.purple.shade100,
                            child: Text(
                              exam.originalId ?? exam.id.substring(0, 2),
                              style: TextStyle(
                                color: Colors.purple.shade800,
                                fontWeight: FontWeight.bold,
                                fontSize: 12,
                              ),
                            ),
                          ),
                          title: Text(
                            exam.title,
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                          ),
                          subtitle: Column(
                            crossAxisAlignment: CrossAxisAlignment.start,
                            children: [
                              Text('${exam.questions.length}题 • ${exam.duration}分钟'),
                              if (exam.originalId != null)
                                Text(
                                  'ID: ${exam.originalId}',
                                  style: TextStyle(
                                    fontSize: 12,
                                    color: Colors.grey.shade600,
                                  ),
                                ),
                            ],
                          ),
                          trailing: PopupMenuButton<String>(
                            onSelected: (value) {
                              if (value == 'delete') {
                                _showDeleteExamConfirmDialog(exam);
                              } else if (value == 'details') {
                                _showExamDetailsDialog(exam);
                              }
                            },
                            itemBuilder: (context) => [
                              PopupMenuItem(
                                value: 'details',
                                child: Row(
                                  children: [
                                    Icon(Icons.info_outline, size: 16),
                                    SizedBox(width: 8),
                                    Text('查看详情'),
                                  ],
                                ),
                              ),
                              PopupMenuItem(
                                value: 'delete',
                                child: Row(
                                  children: [
                                    Icon(Icons.delete_outline, size: 16, color: Colors.red),
                                    SizedBox(width: 8),
                                    Text('删除试题', style: TextStyle(color: Colors.red)),
                                  ],
                                ),
                              ),
                            ],
                          ),
                        ),
                      );
                    },
                  ),
                ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              Navigator.pop(context);
            },
            child: Text('关闭'),
          ),
          if (_exams.isNotEmpty)
            TextButton(
              onPressed: () {
                Navigator.pop(context);
                _showClearAllExamsDialog();
              },
              child: Text(
                '清空所有试题',
                style: TextStyle(color: Colors.red),
              ),
            ),
        ],
      ),
    );
  }
  
  // 获取总题目数
  int _getTotalQuestions() {
    int total = 0;
    for (var exam in _exams) {
      total += exam.questions.length;
    }
    return total;
  }
  
  // 获取平均时长
  int _getAverageDuration() {
    if (_exams.isEmpty) return 0;
    int total = 0;
    for (var exam in _exams) {
      total += exam.duration;
    }
    return (total / _exams.length).round();
  }
  
  // 显示试题详情对话框
  void _showExamDetailsDialog(Exam exam) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('试题详情'),
        content: Container(
          width: double.maxFinite,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildDetailRow('试题ID', exam.originalId ?? exam.id),
              _buildDetailRow('试题名称', exam.title),
              _buildDetailRow('试题描述', exam.description),
              _buildDetailRow('考试时长', '${exam.duration} 分钟'),
              _buildDetailRow('题目数量', '${exam.questions.length} 题'),
              _buildDetailRow('总分', '${exam.totalScore} 分'),
              SizedBox(height: 12),
              Text(
                '题型分布:',
                style: TextStyle(fontWeight: FontWeight.bold),
              ),
              SizedBox(height: 8),
              ..._getQuestionTypeDistribution(exam.questions).entries.map((entry) =>
                Padding(
                  padding: EdgeInsets.only(left: 16, bottom: 4),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(entry.key),
                      Text('${entry.value} 题'),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('关闭'),
          ),
        ],
      ),
    );
  }
  
  // 构建详情行
  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              '$label:',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
          ),
          Expanded(
            child: Text(value),
          ),
        ],
      ),
    );
  }
  
  // 获取题型分布
  Map<String, int> _getQuestionTypeDistribution(List<Question> questions) {
    Map<String, int> distribution = {};
    for (var question in questions) {
      String typeName;
      switch (question.type) {
        case QuestionType.singleChoice:
          typeName = '单选题';
          break;
        case QuestionType.multipleChoice:
          typeName = '多选题';
          break;
        case QuestionType.fillBlank:
          typeName = '填空题';
          break;
        case QuestionType.trueOrFalse:
          typeName = '判断题';
          break;
        case QuestionType.shortAnswer:
          typeName = '简答题';
          break;
      }
      distribution[typeName] = (distribution[typeName] ?? 0) + 1;
    }
    return distribution;
  }
  
  // 显示删除试题确认对话框
  void _showDeleteExamConfirmDialog(Exam exam) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('确认删除'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('确定要删除以下试题吗？'),
            SizedBox(height: 12),
            Container(
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.red.shade50,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.red.shade200),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    exam.title,
                    style: TextStyle(fontWeight: FontWeight.bold),
                  ),
                  SizedBox(height: 4),
                  Text('${exam.questions.length}题 • ${exam.duration}分钟'),
                  if (exam.originalId != null)
                    Text(
                      'ID: ${exam.originalId}',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.grey.shade600,
                      ),
                    ),
                ],
              ),
            ),
            SizedBox(height: 12),
            Text(
              '⚠️ 此操作不可恢复，所有相关的考试记录也将被清除。',
              style: TextStyle(
                color: Colors.red.shade700,
                fontSize: 12,
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              _deleteExam(exam);
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: Text('确认删除'),
          ),
        ],
      ),
    );
  }
  
  // 删除试题
  Future<void> _deleteExam(Exam exam) async {
    try {
      // 添加调试日志
      debugPrint('开始删除考试: ID=${exam.id}, 标题=${exam.title}');
      
      // 先检查ExamService中是否存在此考试
      final examInService = ExamService.getExamById(exam.id);
      if (examInService == null) {
        debugPrint('警告：ExamService中不存在此考试: ${exam.id}');
        // 从UI列表中移除此考试
        setState(() {
          _exams.removeWhere((e) => e.id == exam.id);
        });
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('试题 "${exam.title}" 不存在，已从列表中移除'),
            backgroundColor: Colors.orange,
          ),
        );
        return;
      }
      
      // 删除试题
      final success = await ExamService.removeExam(exam.id);
      
      if (!success) {
        debugPrint('ExamService.removeExam 返回失败');
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('删除试题失败：试题不存在或已被删除'),
            backgroundColor: Colors.red,
          ),
        );
        return;
      }
      
      // 清除所有用户相关的考试状态和结果
      final prefs = await SharedPreferences.getInstance();
      final keys = prefs.getKeys();
      
      // 查找并删除与此考试相关的所有数据
      for (String key in keys) {
        if (key.contains(exam.id)) {
          await prefs.remove(key);
        }
      }
      
      // 重新加载试题列表
      await _loadExams();
      
      // 关闭当前的试题管理对话框并重新打开以刷新统计数据
      Navigator.of(context).pop();
      _showExamManagementDialog();
      
      // 显示成功消息
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('试题 "${exam.title}" 已删除'),
          backgroundColor: Colors.green,
        ),
      );
    } catch (e) {
      debugPrint('删除试题时出错: $e');
      // 显示错误消息
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('删除失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
  
  // 显示清空所有试题确认对话框
  void _showClearAllExamsDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('确认清空'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('确定要清空设备上的所有试题吗？'),
            SizedBox(height: 12),
            Container(
              padding: EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.red.shade50,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(color: Colors.red.shade200),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('将要删除:'),
                  SizedBox(height: 8),
                  Text('• ${_exams.length} 套试题'),
                  Text('• ${_getTotalQuestions()} 道题目'),
                  Text('• 所有相关的考试记录'),
                ],
              ),
            ),
            SizedBox(height: 12),
            Text(
              '⚠️ 此操作不可恢复，请谨慎操作！',
              style: TextStyle(
                color: Colors.red.shade700,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              _clearAllExams();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: Text('确认清空'),
          ),
        ],
      ),
    );
  }
  
  // 清空所有试题
  Future<void> _clearAllExams() async {
    setState(() {
      _isLoading = true;
    });
    
    try {
      // 清空所有试题
      await ExamService.clearAllExams();
      
      // 清除所有考试相关的SharedPreferences数据
      final prefs = await SharedPreferences.getInstance();
      final keys = prefs.getKeys().toList();
      
      for (String key in keys) {
        if (key.startsWith('exam_state_') || 
            key.startsWith('exam_result_')) {
          await prefs.remove(key);
        }
      }
      
      // 重新加载试题列表
      await _loadExams();
      
      // 关闭当前的试题管理对话框并重新打开以刷新统计数据
      Navigator.of(context).pop();
      _showExamManagementDialog();
      
      // 显示成功消息
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('所有试题已清空'),
          backgroundColor: Colors.green,
        ),
      );
    } catch (e) {
      // 显示错误消息
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('清空失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    } finally {
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 注意：此方法已被删除，现在使用集成在恢复考试对话框中的管理员密码验证

  // 显示管理员密码验证对话框
  void _showAdminPasswordDialog(Map<String, dynamic> exam) {
    // 确保密码控制器是新的实例，避免使用已释放的控制器
    final TextEditingController passwordController = TextEditingController();
    
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Text('管理员验证'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('请输入管理员密码以恢复考试'),
            SizedBox(height: 16),
            TextField(
              controller: passwordController,
              obscureText: true,
              decoration: InputDecoration(
                labelText: '管理员密码',
                border: OutlineInputBorder(),
              ),
            ),
          ],
        ),
        actions: [
          ElevatedButton(
            onPressed: () {
              // 验证管理员登录密码
              if (UserData.verifyAdminPassword(passwordController.text)) {
                // 确保在关闭对话框前清理控制器状态
                String examId = exam['examId'];
                int remainingSeconds = exam['remainingSeconds'];

                // 关闭对话框
                if (mounted) {
                  Navigator.of(context).pop();
                }

                // 使用PostFrameCallback确保在正确的构建周期执行
                WidgetsBinding.instance.addPostFrameCallback((_) {
                  if (mounted) {
                    // 直接调用恢复考试功能
                    _resumeExam(examId, remainingSeconds);
                  }
                });
              } else {
                // 密码错误，显示错误信息
                if (mounted) {
                  ScaffoldMessenger.of(context).showSnackBar(
                    SnackBar(
                      content: Text('密码错误，请重试'),
                      backgroundColor: Colors.red,
                    ),
                  );
                }
              }
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.blue,
              foregroundColor: Colors.white,
            ),
            child: Text('验证'),
          ),
        ],
      ),
    ).then((_) {
      // 确保对话框关闭后，控制器被安全释放
      try {
        passwordController.dispose();
      } catch (e) {
        // 忽略重复释放的错误
      }
    });
  }
  
  // 恢复考试
  Future<void> _resumeExam(String examId, int remainingSeconds) async {
    // 显示加载指示器
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => Center(
        child: CircularProgressIndicator(),
      ),
    );
    
    try {
      // 获取考试信息
      final exam = ExamService.getExamById(examId);
      if (exam == null) {
        if (mounted) {
          Navigator.of(context).pop(); // 关闭加载指示器
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('找不到考试信息'),
              backgroundColor: Colors.red,
            ),
          );
        }
        return;
      }
      
      // 恢复考试状态，调整剩余时间
      final examState = await ExamStateService.resumeExam(
        examId, 
        adjustedRemainingSeconds: remainingSeconds
      );
      
      if (examState == null) {
        if (mounted) {
          Navigator.of(context).pop(); // 关闭加载指示器
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('恢复考试状态失败'),
              backgroundColor: Colors.red,
            ),
          );
        }
        return;
      }
      
      // 确保在状态变化前检查组件是否还在树中
      if (!mounted) return;
      
      // 关闭加载指示器
      Navigator.of(context).pop();
      
      // 导航到考试页面 - 使用pushReplacement防止返回到首页
      await Navigator.of(context).pushReplacement(
        MaterialPageRoute(
          builder: (context) => ExamScreen(
            exam: exam, 
            initialState: examState,
          ),
          settings: RouteSettings(name: 'ExamScreen'),
        ),
      );
      
      // 注意：因为使用了pushReplacement，当考试结束后不会回到这个页面
      // 而是会导航到结果页面，所以不需要在这里再检查未完成考试
    } catch (e) {
      debugPrint('恢复考试时出错: $e');
      // 关闭加载指示器
      if (mounted) {
        Navigator.of(context).pop();
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('恢复考试时出错: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  // 学生恢复考试（不需要管理员密码）
  Future<void> _resumeExamForStudent(Map<String, dynamic> examData) async {
    // 防止重复调用
    if (_isLoading) {
      AppLogger.log('⚠️ 正在恢复考试中，跳过重复调用');
      return;
    }

    try {
      AppLogger.log('=== 开始恢复学生考试 ===');
      AppLogger.log('考试数据: $examData');
      AppLogger.log('方法被成功调用');
    } catch (e) {
      AppLogger.log('❌ 方法调用异常: $e');
      return;
    }

    // 使用PostFrameCallback确保在正确的构建周期执行状态更新
    WidgetsBinding.instance.addPostFrameCallback((_) async {
      if (!mounted) return;

      // 设置加载状态
      setState(() {
        _isLoading = true;
      });

      // 显示加载指示器
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const Center(
          child: CircularProgressIndicator(),
        ),
      );

      // 执行实际的恢复逻辑
      await _performExamRecovery(examData);
    });
  }

  // 执行实际的考试恢复逻辑
  Future<void> _performExamRecovery(Map<String, dynamic> examData) async {
    try {
      final examId = examData['examId'];
      final remainingSeconds = examData['remainingSeconds'];

      AppLogger.log('考试ID: $examId');
      AppLogger.log('剩余时间: $remainingSeconds 秒');

      // 获取考试信息
      AppLogger.log('正在查找考试ID: $examId');

      // 获取所有可用的考试ID进行对比
      final allExams = ExamService.getAllExams();
      AppLogger.log('系统中共有 ${allExams.length} 个考试:');
      for (var examItem in allExams) {
        AppLogger.log('  - 考试ID: ${examItem.id}, 标题: ${examItem.title}');
        if (examItem.originalId != null) {
          AppLogger.log('    原始ID: ${examItem.originalId}');
        }
      }

      // 首先尝试精确匹配
      Exam? exam = ExamService.getExamById(examId);
      AppLogger.log('精确匹配结果: ${exam != null ? '成功' : '失败'}');

      // 如果精确匹配失败，尝试各种匹配策略
      if (exam == null) {
        AppLogger.log('精确匹配失败，尝试其他匹配策略...');

        // 策略1: 移除 exam_ 前缀后匹配
        final examIdWithoutPrefix = examId.replaceAll('exam_', '');
        exam = allExams.where((e) => e.id == examIdWithoutPrefix).firstOrNull;
        if (exam != null) {
          AppLogger.log('策略1成功: 移除前缀后匹配到考试 ${exam.id}');
        }

        // 策略2: 通过originalId匹配
        if (exam == null) {
          exam = allExams.where((e) => e.originalId == examId || e.originalId == examIdWithoutPrefix).firstOrNull;
          if (exam != null) {
            AppLogger.log('策略2成功: 通过originalId匹配到考试 ${exam.id}');
          }
        }

        // 策略3: 部分ID匹配
        if (exam == null) {
          exam = allExams.where((e) =>
            e.id.contains(examIdWithoutPrefix) ||
            examIdWithoutPrefix.contains(e.id) ||
            (e.originalId != null && (e.originalId!.contains(examIdWithoutPrefix) || examIdWithoutPrefix.contains(e.originalId!)))
          ).firstOrNull;
          if (exam != null) {
            AppLogger.log('策略3成功: 部分匹配到考试 ${exam.id}');
          }
        }
      }

      // 如果所有匹配策略都失败，尝试标题匹配作为最后手段
      if (exam == null) {
        AppLogger.log('所有ID匹配策略失败，尝试标题匹配...');

        // 策略4: 通过标题匹配（如果考试状态中有标题信息）
        if (examData.containsKey('examTitle')) {
          final examTitle = examData['examTitle'];
          exam = allExams.where((e) => e.title == examTitle).firstOrNull;
          if (exam != null) {
            AppLogger.log('策略4成功: 通过标题匹配到考试 ${exam.id}');
          }
        }

        // 策略5: 如果只有一个考试，直接使用
        if (exam == null && allExams.length == 1) {
          exam = allExams.first;
          AppLogger.log('策略5成功: 系统中只有一个考试，直接使用 ${exam.id}');
        }
      }

      if (exam == null) {
        AppLogger.log('❌ 找不到考试信息，考试ID: $examId');
        if (mounted) {
          Navigator.of(context).pop(); // 关闭加载指示器

          // 使用PostFrameCallback确保在下一个构建周期执行后续操作
          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (mounted) {
              setState(() {
                _isLoading = false;
              });
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('找不到考试信息'),
                  backgroundColor: Colors.red,
                ),
              );
            }
          });
        }
        return;
      }

      // 继续执行恢复逻辑
      await _continueExamRecovery(exam, examId, remainingSeconds);
    } catch (e) {
      AppLogger.log('❌ 恢复考试时出错: $e');
      if (mounted) {
        Navigator.of(context).pop(); // 关闭加载指示器

        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            setState(() {
              _isLoading = false;
            });
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('恢复考试失败: $e'),
                backgroundColor: Colors.red,
              ),
            );
          }
        });
      }
    }
  }

  // 格式化最后更新时间（只显示时分秒）
  String _formatLastUpdatedTime(DateTime dateTime) {
    return '${dateTime.hour.toString().padLeft(2, '0')}:${dateTime.minute.toString().padLeft(2, '0')}:${dateTime.second.toString().padLeft(2, '0')}';
  }

  // 计算已答题数（使用与考试页面相同的逻辑）
  int _calculateAnsweredQuestions(Map<String, dynamic> answers) {
    // 排除系统字段，只计算实际的题目答案
    final systemFields = {'_active_session', '_last_activity', '_answerImages'};

    int answeredCount = 0;

    // 遍历所有非系统字段的答案
    for (var entry in answers.entries) {
      if (systemFields.contains(entry.key)) {
        continue; // 跳过系统字段
      }

      final questionId = entry.key;
      final answer = entry.value;

      // 使用与考试页面相同的判断逻辑
      bool hasValidAnswer = _isAnswerValid(questionId, answer, answers);

      if (hasValidAnswer) {
        answeredCount++;
      }
    }

    return answeredCount;
  }

  // 判断答案是否有效（与ExamScreen中的逻辑保持一致）
  bool _isAnswerValid(String questionId, dynamic answer, Map<String, dynamic> allAnswers) {
    if (answer == null) return false;

    // 检查文字答案
    bool hasTextAnswer = false;

    if (answer is String) {
      hasTextAnswer = answer.trim().isNotEmpty;
    } else if (answer is List) {
      if (answer.isEmpty) {
        hasTextAnswer = false;
      } else {
        // 对于多选题或多空填空题
        hasTextAnswer = answer.any((item) =>
          item != null && item.toString().trim().isNotEmpty
        );
      }
    }

    // 检查照片答案
    bool hasPhotoAnswer = false;
    if (allAnswers.containsKey('_answerImages')) {
      final answerImages = allAnswers['_answerImages'] as Map<String, dynamic>?;
      if (answerImages != null && answerImages.containsKey(questionId)) {
        final images = answerImages[questionId];
        if (images is List && images.isNotEmpty) {
          hasPhotoAnswer = true;
        }
      }
    }

    return hasTextAnswer || hasPhotoAnswer;
  }

  // 继续执行考试恢复逻辑的辅助方法
  Future<void> _continueExamRecovery(Exam exam, String examId, int remainingSeconds) async {
    try {

      AppLogger.log('考试信息: ${exam.title}');

      // 获取当前用户的考试状态
      final currentUser = UserData.currentUser;
      if (currentUser == null) {
        AppLogger.log('❌ 当前用户为空');
        if (mounted) {
          Navigator.of(context).pop();

          // 使用PostFrameCallback确保在下一个构建周期执行后续操作
          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (mounted) {
              setState(() {
                _isLoading = false;
              });
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('用户信息错误'),
                  backgroundColor: Colors.red,
                ),
              );
            }
          });
        }
        return;
      }

      AppLogger.log('当前用户: ${currentUser.id}');

      // 获取考试状态
      final examState = await ExamStateService.getExamState(examId, currentUser.id);
      AppLogger.log('获取考试状态结果: ${examState != null ? '成功' : '失败'}');

      if (examState == null) {
        AppLogger.log('❌ 找不到考试状态');
        if (mounted) {
          Navigator.of(context).pop();

          // 使用PostFrameCallback确保在下一个构建周期执行后续操作
          WidgetsBinding.instance.addPostFrameCallback((_) {
            if (mounted) {
              setState(() {
                _isLoading = false;
              });
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('找不到考试状态'),
                  backgroundColor: Colors.red,
                ),
              );
            }
          });
        }
        return;
      }

      AppLogger.log('考试状态: ${examState.status}');
      AppLogger.log('答案数量: ${examState.answers.length}');

      // 确保在状态变化前检查组件是否还在树中
      if (!mounted) return;

      // 关闭加载指示器
      Navigator.of(context).pop();

      // 使用PostFrameCallback确保在下一个构建周期执行后续操作
      WidgetsBinding.instance.addPostFrameCallback((_) async {
        if (!mounted) return;

        // 重置加载状态
        setState(() {
          _isLoading = false;
        });

        // 延迟导航，确保状态更新完成
        await Future.delayed(Duration(milliseconds: 100));

        if (!mounted) return;

        AppLogger.log('✅ 准备导航到考试页面');

        // 导航到考试页面
        await Navigator.of(context).push(
          MaterialPageRoute(
            builder: (context) => ExamScreen(
              exam: exam,
              initialState: examState,
            ),
            settings: const RouteSettings(name: 'ExamScreen'),
          ),
        );

        AppLogger.log('考试页面已关闭，返回首页');

        // 考试结束后重新检查未完成考试
        // 添加延迟，给主动离开的删除操作足够时间完成
        if (mounted) {
          Future.delayed(Duration(milliseconds: 1000), () {
            if (mounted) {
              AppLogger.log('延迟检查未完成考试（给删除操作时间）');
              _checkIncompleteExams();
            }
          });
        }
      });

    } catch (e) {
      AppLogger.log('❌ 恢复考试时出错: $e');
      // 关闭加载指示器
      if (mounted) {
        Navigator.of(context).pop();

        // 使用PostFrameCallback确保在下一个构建周期执行后续操作
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            setState(() {
              _isLoading = false;
            });
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(
                content: Text('恢复考试时出错: $e'),
                backgroundColor: Colors.red,
              ),
            );
          }
        });
      }
    }
  }

  // 格式化时间（秒 -> HH:MM:SS）
  String _formatTime(int seconds) {
    int hours = seconds ~/ 3600;
    int minutes = (seconds % 3600) ~/ 60;
    int secs = seconds % 60;
    
    return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
  }
  
  // 显示专用设备配置对话框
  void _showDedicatedDeviceDialog() async {
    bool isDedicated = await DeviceConfigService.isDedicatedDevice();
    final dedicatedPath = await DeviceConfigService.getDedicatedDevicePath();
    final pathController = TextEditingController(text: dedicatedPath);
    bool isMonitoring = DedicatedDeviceMonitorService.isMonitoring;
    
    showDialog(
      context: context,
      builder: (context) => StatefulBuilder(
        builder: (context, setDialogState) => AlertDialog(
          title: const Row(
            children: [
              Icon(Icons.settings, color: Colors.orange),
              SizedBox(width: 8),
              Text('专用设备配置'),
            ],
          ),
          content: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                const Text(
                  '专用设备模式说明：',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                const Text(
                  '启用专用设备模式后，APP将自动从指定路径读取试卷和考生信息的Excel文件，无需手动导入。开启监控后，系统将每20秒检测一次路径下的文件变化并自动加载。',
                  style: TextStyle(color: Colors.grey),
                ),
                const SizedBox(height: 16),
                
                // 专用设备开关
                Row(
                  children: [
                    const Text('启用专用设备模式：'),
                    const Spacer(),
                    Switch(
                      value: isDedicated,
                      onChanged: (value) async {
                        setDialogState(() {
                          isDedicated = value;
                        });
                        await DeviceConfigService.setDedicatedDevice(value);
                        
                        // 根据专用设备状态启动或停止监控
                        if (value) {
                          await DedicatedDeviceMonitorService.startMonitoring();
                        } else {
                          DedicatedDeviceMonitorService.stopMonitoring();
                        }
                        
                        setDialogState(() {
                          isMonitoring = DedicatedDeviceMonitorService.isMonitoring;
                        });
                      },
                    ),
                  ],
                ),
                
                // 监控状态显示
                if (isDedicated) ...[
                  const SizedBox(height: 16),
                  Container(
                    padding: const EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: isMonitoring ? Colors.green.shade50 : Colors.orange.shade50,
                      border: Border.all(
                        color: isMonitoring ? Colors.green.shade300 : Colors.orange.shade300,
                      ),
                      borderRadius: BorderRadius.circular(8),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Icon(
                              isMonitoring ? Icons.monitor : Icons.monitor_outlined,
                              color: isMonitoring ? Colors.green : Colors.orange,
                              size: 20,
                            ),
                            const SizedBox(width: 8),
                            Text(
                              '文件监控状态：${isMonitoring ? "运行中" : "已停止"}',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: isMonitoring ? Colors.green.shade700 : Colors.orange.shade700,
                              ),
                            ),
                            const Spacer(),
                            Switch(
                              value: isMonitoring,
                              onChanged: (value) async {
                                if (value) {
                                  await DedicatedDeviceMonitorService.startMonitoring();
                                } else {
                                  DedicatedDeviceMonitorService.stopMonitoring();
                                }
                                setDialogState(() {
                                  isMonitoring = DedicatedDeviceMonitorService.isMonitoring;
                                });
                              },
                            ),
                          ],
                        ),
                        const SizedBox(height: 8),
                        Text(
                          isMonitoring ? '每20秒自动检测文件变化' : '手动检测模式',
                          style: TextStyle(
                            fontSize: 12,
                            color: isMonitoring ? Colors.green.shade600 : Colors.orange.shade600,
                          ),
                        ),
                      ],
                    ),
                  ),
                ],
                
                const SizedBox(height: 16),
                
                // 路径配置
                const Text(
                  '专用设备路径：',
                  style: TextStyle(fontWeight: FontWeight.bold),
                ),
                const SizedBox(height: 8),
                TextField(
                  controller: pathController,
                  enabled: isDedicated,
                  decoration: const InputDecoration(
                    labelText: 'Excel文件路径',
                    hintText: '/data/userdata/com.westone.examapp',
                    border: OutlineInputBorder(),
                    helperText: '请输入包含Excel文件的目录路径',
                  ),
                  maxLines: 2,
                ),
                
                const SizedBox(height: 16),
                
                // 文件要求说明
                Container(
                  padding: const EdgeInsets.all(12),
                  decoration: BoxDecoration(
                    color: Colors.blue.shade50,
                    border: Border.all(color: Colors.blue.shade200),
                    borderRadius: BorderRadius.circular(8),
                  ),
                  child: const Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        '文件要求：',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      SizedBox(height: 4),
                      Text('• 学生信息.xlsx - 包含学生信息'),
                      Text('• 试题信息.xlsx - 包含考试题目'),
                      Text('• 考试须知.xlsx - 包含考试说明'),
                    ],
                  ),
                ),
                
                if (isDedicated) ...[
                  const SizedBox(height: 16),
                  Row(
                    children: [
                      Expanded(
                        child: ElevatedButton.icon(
                          icon: const Icon(Icons.download),
                          label: const Text('手动加载'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.green,
                            foregroundColor: Colors.white,
                          ),
                          onPressed: () {
                            Navigator.of(context).pop();
                            _loadFromDedicatedPath();
                          },
                        ),
                      ),
                      const SizedBox(width: 8),
                      Expanded(
                        child: ElevatedButton.icon(
                          icon: const Icon(Icons.search),
                          label: const Text('立即检测'),
                          style: ElevatedButton.styleFrom(
                            backgroundColor: Colors.blue,
                            foregroundColor: Colors.white,
                          ),
                          onPressed: () async {
                            Navigator.of(context).pop();
                            await _performManualCheck();
                          },
                        ),
                      ),
                    ],
                  ),
                  const SizedBox(height: 8),
                  SizedBox(
                    width: double.infinity,
                    child: ElevatedButton.icon(
                      icon: const Icon(Icons.security),
                      label: const Text('权限测试'),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Colors.orange,
                        foregroundColor: Colors.white,
                      ),
                      onPressed: () async {
                        Navigator.of(context).pop();
                        await _testDedicatedPathPermissions();
                      },
                    ),
                  ),
                ],
              ],
            ),
          ),
          actions: [
            TextButton(
              onPressed: () => Navigator.of(context).pop(),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () async {
                // 保存路径配置
                await DeviceConfigService.setDedicatedDevicePath(pathController.text.trim());
                
                // 如果专用设备模式已启用，重启监控服务以使用新路径
                if (isDedicated) {
                  await DedicatedDeviceMonitorService.restartMonitoring();
                }
                
                if (mounted) {
                  Navigator.of(context).pop();
                  ScaffoldMessenger.of(context).showSnackBar(
                    const SnackBar(
                      content: Text('专用设备配置已保存'),
                      backgroundColor: Colors.green,
                    ),
                  );
                }
              },
              child: const Text('保存配置'),
            ),
          ],
        ),
      ),
    ).then((_) {
      pathController.dispose();
    });
  }
  
  // 显示批量清除试卷对话框
  void _showBatchClearExamsDialog() async {
    final statistics = ExamService.getDataStatistics();
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Row(
          children: [
            Icon(Icons.warning, color: Colors.red),
            SizedBox(width: 8),
            Text('批量清除试卷'),
          ],
        ),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const Text(
                '确认批量清除操作',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
              ),
              const SizedBox(height: 16),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.yellow.shade50,
                  border: Border.all(color: Colors.yellow.shade300),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '将要清除的数据：',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    Text('• 试卷数量：${statistics['exams']} 套'),
                    Text('• 分配关系：${statistics['assignments']} 条'),
                  ],
                ),
              ),
              const SizedBox(height: 16),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.green.shade50,
                  border: Border.all(color: Colors.green.shade300),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    const Text(
                      '将要保留的数据：',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    Text('• 考试结果：${statistics['results']} 条'),
                    const Text('• 学生信息：完整保留'),
                    const Text('• 考试答题图片：完整保留'),
                  ],
                ),
              ),
              const SizedBox(height: 16),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Colors.red.shade50,
                  border: Border.all(color: Colors.red.shade300),
                  borderRadius: BorderRadius.circular(8),
                ),
                child: const Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      '重要提醒：',
                      style: TextStyle(fontWeight: FontWeight.bold, color: Colors.red),
                    ),
                    SizedBox(height: 8),
                    Text('• 此操作不可逆，请谨慎操作'),
                    Text('• 清除后需要重新导入试卷'),
                    Text('• 学生已完成的考试结果不会受影响'),
                  ],
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () async {
              Navigator.of(context).pop();
              await _executeBatchClearExams();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: const Text('确认清除'),
          ),
        ],
      ),
    );
  }

  // 执行批量清除试卷
  Future<void> _executeBatchClearExams() async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const AlertDialog(
        content: Row(
          children: [
            CircularProgressIndicator(),
            SizedBox(width: 20),
            Text('正在执行批量清除...'),
          ],
        ),
      ),
    );

    try {
      final result = await ExamService.batchClearExams();
      
      if (mounted) {
        Navigator.of(context).pop(); // 关闭加载对话框
        
        // 刷新界面
        _loadExams();
        
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text(
              result['success'] ? '清除完成' : '清除失败',
              style: TextStyle(
                color: result['success'] ? Colors.green : Colors.red,
              ),
            ),
            content: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(result['message']),
                  if (result['details'] != null) ...[
                    const SizedBox(height: 12),
                    const Text(
                      '详细信息：',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    Text(result['details']['summary']),
                    if (result['success']) ...[
                      const SizedBox(height: 8),
                      Text('• 清除试卷：${result['details']['clearedExams']} 套'),
                      Text('• 保留结果：${result['details']['preservedResults']} 条'),
                    ],
                  ],
                ],
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('确定'),
              ),
            ],
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        Navigator.of(context).pop();
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('批量清除失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  // 显示数据统计信息
  void _showDataStatistics() {
    final statistics = ExamService.getDataStatistics();
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Row(
          children: [
            Icon(Icons.analytics, color: Colors.teal),
            SizedBox(width: 8),
            Text('数据统计'),
          ],
        ),
        content: SingleChildScrollView(
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              _buildStatisticCard(
                '试卷数据',
                [
                  {'label': '试卷总数', 'value': '${statistics['exams']} 套', 'icon': Icons.assignment},
                  {'label': '分配关系', 'value': '${statistics['assignments']} 条', 'icon': Icons.link},
                ],
                Colors.blue,
              ),
              const SizedBox(height: 12),
              _buildStatisticCard(
                '考试结果',
                [
                  {'label': '完成考试', 'value': '${statistics['results']} 人次', 'icon': Icons.check_circle},
                  {'label': '学生总数', 'value': '${StudentService.getStudents().length} 人', 'icon': Icons.people},
                ],
                Colors.green,
              ),
              const SizedBox(height: 12),
              _buildStatisticCard(
                '监控状态',
                [
                  {
                    'label': '专用设备',
                    'value': UserData.currentUser != null ? '已启用' : '未启用',
                    'icon': Icons.devices
                  },
                  {
                    'label': '文件监控',
                    'value': DedicatedDeviceMonitorService.isMonitoring ? '运行中' : '已停止',
                    'icon': Icons.monitor
                  },
                ],
                Colors.orange,
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  // 构建统计卡片
  Widget _buildStatisticCard(String title, List<Map<String, dynamic>> items, Color color) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        border: Border.all(color: color.withOpacity(0.3)),
        borderRadius: BorderRadius.circular(8),
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Text(
            title,
            style: TextStyle(
              fontWeight: FontWeight.bold,
              color: color.withOpacity(0.8),
              fontSize: 14,
            ),
          ),
          const SizedBox(height: 8),
          ...items.map((item) => Padding(
            padding: const EdgeInsets.only(bottom: 4),
            child: Row(
              children: [
                Icon(item['icon'], size: 16, color: color.withOpacity(0.7)),
                const SizedBox(width: 8),
                Text('${item['label']}：'),
                const Spacer(),
                Text(
                  item['value'],
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                    color: color.withOpacity(0.9),
                  ),
                ),
              ],
            ),
          )),
        ],
      ),
    );
  }

  // 手动执行监控检测
  Future<void> _performManualCheck() async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const AlertDialog(
        content: Row(
          children: [
            CircularProgressIndicator(),
            SizedBox(width: 20),
            Text('正在检测文件变化...'),
          ],
        ),
      ),
    );
    
    try {
      final result = await DedicatedDeviceMonitorService.performManualCheck();
      
      if (mounted) {
        Navigator.of(context).pop(); // 关闭检测对话框
        
        if (result == null) {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('未检测到文件变化'),
              backgroundColor: Colors.blue,
            ),
          );
        } else {
          showDialog(
            context: context,
            builder: (context) => AlertDialog(
              title: Text(
                result['success'] ? '检测完成' : '检测失败',
                style: TextStyle(
                  color: result['success'] ? Colors.green : Colors.red,
                ),
              ),
              content: SingleChildScrollView(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Text(result['message']),
                    if (result['details'] != null && result['details'].isNotEmpty) ...[
                      const SizedBox(height: 12),
                      const Text(
                        '详细信息：',
                        style: TextStyle(fontWeight: FontWeight.bold),
                      ),
                      const SizedBox(height: 8),
                      ...result['details'].map<Widget>((detail) => Padding(
                        padding: const EdgeInsets.only(bottom: 4),
                        child: Text('• $detail'),
                      )),
                    ],
                  ],
                ),
              ),
              actions: [
                TextButton(
                  onPressed: () {
                    Navigator.of(context).pop();
                    setState(() {}); // 刷新界面
                  },
                  child: const Text('确定'),
                ),
              ],
            ),
          );
        }
      }
    } catch (e) {
      if (mounted) {
        Navigator.of(context).pop();
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('检测失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  // 从专用设备路径加载文件
  Future<void> _loadFromDedicatedPath() async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const AlertDialog(
        content: Row(
          children: [
            CircularProgressIndicator(),
            SizedBox(width: 20),
            Text('正在从专用设备路径加载...'),
          ],
        ),
      ),
    );
    
    try {
      final result = await DeviceConfigService.loadFromDedicatedPath();
      
      if (mounted) {
        Navigator.of(context).pop(); // 关闭加载对话框
        
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Text(
              result['success'] ? '加载完成' : '加载失败',
              style: TextStyle(
                color: result['success'] ? Colors.green : Colors.red,
              ),
            ),
            content: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(result['message']),
                  if (result['details'] != null && result['details'].isNotEmpty) ...[
                    const SizedBox(height: 12),
                    const Text(
                      '详细信息：',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    ...result['details'].map<Widget>((detail) => Padding(
                      padding: const EdgeInsets.only(bottom: 4),
                      child: Text('• $detail'),
                    )),
                  ],
                ],
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('确定'),
              ),
            ],
          ),
        );
        
        // 重新加载考试数据
        if (result['success']) {
          _loadExams();
        }
      }
    } catch (e) {
      if (mounted) {
        Navigator.of(context).pop(); // 关闭加载对话框
        
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('加载失败', style: TextStyle(color: Colors.red)),
            content: Text('从专用设备路径加载失败：$e'),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('确定'),
              ),
            ],
          ),
        );
      }
    }
  }

  // 测试专用设备路径权限
  Future<void> _testDedicatedPathPermissions() async {
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => const AlertDialog(
        content: Row(
          children: [
            CircularProgressIndicator(),
            SizedBox(width: 20),
            Text('正在测试路径权限...'),
          ],
        ),
      ),
    );
    
    try {
      final result = await DeviceConfigService.testDedicatedPathPermissions();
      
      if (mounted) {
        Navigator.of(context).pop(); // 关闭测试对话框
        
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: Row(
              children: [
                Icon(
                  result['success'] ? Icons.check_circle : Icons.error,
                  color: result['success'] ? Colors.green : Colors.red,
                ),
                const SizedBox(width: 8),
                Text(
                  '权限测试结果',
                  style: TextStyle(
                    color: result['success'] ? Colors.green : Colors.red,
                  ),
                ),
              ],
            ),
            content: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text(
                    result['message'],
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  if (result['details'] != null && result['details'].isNotEmpty) ...[
                    const SizedBox(height: 16),
                    const Text(
                      '详细测试结果：',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    ...result['details'].map<Widget>((detail) => Padding(
                      padding: const EdgeInsets.only(bottom: 4),
                      child: Text(detail),
                    )),
                  ],
                  if (result['results'] != null) ...[
                    const SizedBox(height: 16),
                    const Text(
                      '权限摘要：',
                      style: TextStyle(fontWeight: FontWeight.bold),
                    ),
                    const SizedBox(height: 8),
                    ...result['results'].entries.map<Widget>((entry) {
                      final icon = entry.value ? '✓' : '✗';
                      final color = entry.value ? Colors.green : Colors.red;
                      String label;
                      switch (entry.key) {
                        case 'pathExists':
                          label = '路径存在';
                          break;
                        case 'canRead':
                          label = '读取权限';
                          break;
                        case 'canWrite':
                          label = '写入权限';
                          break;
                        case 'canList':
                          label = '列表权限';
                          break;
                        default:
                          label = entry.key;
                      }
                      return Padding(
                        padding: const EdgeInsets.only(bottom: 4),
                        child: Row(
                          children: [
                            Text(
                              icon,
                              style: TextStyle(color: color, fontWeight: FontWeight.bold),
                            ),
                            const SizedBox(width: 8),
                            Text(label),
                          ],
                        ),
                      );
                    }),
                  ],
                  if (!result['success']) ...[
                    const SizedBox(height: 16),
                    Container(
                      padding: const EdgeInsets.all(12),
                      decoration: BoxDecoration(
                        color: Colors.orange.shade50,
                        border: Border.all(color: Colors.orange.shade300),
                        borderRadius: BorderRadius.circular(8),
                      ),
                      child: const Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '解决建议：',
                            style: TextStyle(fontWeight: FontWeight.bold),
                          ),
                          SizedBox(height: 8),
                          Text('• 尝试重启应用'),
                          Text('• 检查路径是否正确'),
                          Text('• 更改为其他可访问的路径'),
                          Text('• 联系设备管理员获取权限'),
                        ],
                      ),
                    ),
                  ],
                ],
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.of(context).pop(),
                child: const Text('确定'),
              ),
            ],
          ),
        );
      }
    } catch (e) {
      if (mounted) {
        Navigator.of(context).pop();
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('权限测试失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  // 显示删除考试记录对话框
  void _showDeleteExamRecordsDialog() async {
    try {
      // 获取所有学生
      final students = StudentService.getStudents();
      if (students.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('没有找到学生数据'),
            backgroundColor: Colors.orange,
          ),
        );
        return;
      }

      // 获取所有考试
      final exams = ExamService.getAllExams();
      if (exams.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('没有找到考试数据'),
            backgroundColor: Colors.orange,
          ),
        );
        return;
      }

      // 构建学生考试记录数据
      List<Map<String, dynamic>> studentRecords = [];
      for (var student in students) {
        for (var exam in exams) {
          final examState = await ExamStateService.getExamState(exam.id, student.id);
          final examResult = await ExamStateService.getExamResult(exam.id, student.id);

          if (examState != null || examResult != null) {
            studentRecords.add({
              'studentId': student.id,
              'studentName': student.name,
              'examId': exam.id,
              'examTitle': exam.title,
              'hasState': examState != null,
              'hasResult': examResult != null,
              'status': examResult != null ? '已完成' : (examState != null ? '进行中' : '未开始'),
              'submittedAt': examResult?.submittedAt?.toString() ?? '',
            });
          }
        }
      }

      if (studentRecords.isEmpty) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('没有找到任何考试记录'),
            backgroundColor: Colors.blue,
          ),
        );
        return;
      }

      // 显示删除对话框
      showDialog(
        context: context,
        builder: (context) => _buildDeleteRecordsDialog(studentRecords),
      );
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('加载考试记录失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  // 构建删除记录对话框
  Widget _buildDeleteRecordsDialog(List<Map<String, dynamic>> records) {
    return AlertDialog(
      title: Row(
        children: [
          Icon(Icons.delete_sweep, color: Colors.red.shade700),
          const SizedBox(width: 8),
          const Text('删除考试记录'),
        ],
      ),
      content: Container(
        width: double.maxFinite,
        height: 400,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '找到 ${records.length} 条考试记录',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
                color: Colors.grey.shade700,
              ),
            ),
            const SizedBox(height: 8),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.red.shade50,
                border: Border.all(color: Colors.red.shade300),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                children: [
                  Icon(Icons.warning, color: Colors.red.shade700, size: 20),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      '删除后，学生可以重新参加对应的考试',
                      style: TextStyle(
                        color: Colors.red.shade800,
                        fontSize: 14,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 16),
            Expanded(
              child: ListView.builder(
                itemCount: records.length,
                itemBuilder: (context, index) {
                  final record = records[index];
                  return Card(
                    margin: const EdgeInsets.only(bottom: 8),
                    child: ListTile(
                      leading: CircleAvatar(
                        backgroundColor: record['status'] == '已完成'
                            ? Colors.green.shade100
                            : Colors.orange.shade100,
                        child: Icon(
                          record['status'] == '已完成'
                              ? Icons.check_circle
                              : Icons.access_time,
                          color: record['status'] == '已完成'
                              ? Colors.green.shade700
                              : Colors.orange.shade700,
                          size: 20,
                        ),
                      ),
                      title: Text(
                        record['studentName'],
                        style: const TextStyle(fontWeight: FontWeight.bold),
                      ),
                      subtitle: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('考试: ${record['examTitle']}'),
                          Text(
                            '状态: ${record['status']}',
                            style: TextStyle(
                              color: record['status'] == '已完成'
                                  ? Colors.green.shade700
                                  : Colors.orange.shade700,
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          if (record['submittedAt'].isNotEmpty)
                            Text(
                              '提交时间: ${record['submittedAt']}',
                              style: TextStyle(
                                fontSize: 12,
                                color: Colors.grey.shade600,
                              ),
                            ),
                        ],
                      ),
                      trailing: IconButton(
                        icon: Icon(Icons.delete, color: Colors.red.shade600),
                        onPressed: () => _deleteExamRecord(record),
                      ),
                    ),
                  );
                },
              ),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () => Navigator.of(context).pop(),
          child: const Text('关闭'),
        ),
        ElevatedButton(
          onPressed: () => _deleteAllRecords(records),
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.red.shade700,
            foregroundColor: Colors.white,
          ),
          child: const Text('删除全部'),
        ),
      ],
    );
  }

  // 删除单个考试记录
  void _deleteExamRecord(Map<String, dynamic> record) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('确定要删除以下考试记录吗？'),
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.grey.shade100,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text('学生: ${record['studentName']}'),
                  Text('考试: ${record['examTitle']}'),
                  Text('状态: ${record['status']}'),
                ],
              ),
            ),
            const SizedBox(height: 12),
            Text(
              '删除后，该学生可以重新参加此考试。',
              style: TextStyle(
                color: Colors.red.shade700,
                fontSize: 14,
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () => Navigator.of(context).pop(true),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red.shade700,
              foregroundColor: Colors.white,
            ),
            child: const Text('确认删除'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        // 删除考试状态和结果
        final stateDeleted = await ExamStateService.removeExamState(
          record['examId'],
          record['studentId']
        );
        final resultDeleted = await ExamStateService.removeExamResult(
          record['examId'],
          record['studentId']
        );

        if (stateDeleted || resultDeleted) {
          ScaffoldMessenger.of(context).showSnackBar(
            SnackBar(
              content: Text('已删除 ${record['studentName']} 的考试记录'),
              backgroundColor: Colors.green,
            ),
          );

          // 关闭对话框并重新打开以刷新数据
          Navigator.of(context).pop();
          _showDeleteExamRecordsDialog();
        } else {
          ScaffoldMessenger.of(context).showSnackBar(
            const SnackBar(
              content: Text('删除失败，请重试'),
              backgroundColor: Colors.red,
            ),
          );
        }
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('删除失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  // 删除所有考试记录
  void _deleteAllRecords(List<Map<String, dynamic>> records) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.warning, color: Colors.red.shade700),
            const SizedBox(width: 8),
            const Text('确认删除全部'),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('确定要删除所有 ${records.length} 条考试记录吗？'),
            const SizedBox(height: 16),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Colors.red.shade50,
                border: Border.all(color: Colors.red.shade300),
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                children: [
                  Icon(Icons.warning, color: Colors.red.shade700, size: 20),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      '此操作不可撤销！删除后，所有学生都可以重新参加对应的考试。',
                      style: TextStyle(
                        color: Colors.red.shade800,
                        fontSize: 14,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.of(context).pop(false),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () => Navigator.of(context).pop(true),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red.shade700,
              foregroundColor: Colors.white,
            ),
            child: const Text('确认删除全部'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        int deletedCount = 0;

        // 显示进度对话框
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => AlertDialog(
            content: Row(
              children: [
                const CircularProgressIndicator(),
                const SizedBox(width: 16),
                const Text('正在删除考试记录...'),
              ],
            ),
          ),
        );

        // 逐个删除记录
        for (var record in records) {
          final stateDeleted = await ExamStateService.removeExamState(
            record['examId'],
            record['studentId']
          );
          final resultDeleted = await ExamStateService.removeExamResult(
            record['examId'],
            record['studentId']
          );

          if (stateDeleted || resultDeleted) {
            deletedCount++;
          }
        }

        // 关闭进度对话框
        Navigator.of(context).pop();

        // 关闭删除对话框
        Navigator.of(context).pop();

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('成功删除 $deletedCount 条考试记录'),
            backgroundColor: Colors.green,
          ),
        );
      } catch (e) {
        // 关闭进度对话框
        Navigator.of(context).pop();

        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('批量删除失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  // 显示管理员设置对话框
  void _showAdminSettingsDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Row(
          children: [
            Icon(Icons.settings, color: Colors.blue),
            SizedBox(width: 8),
            Text('管理员设置'),
          ],
        ),
        content: SizedBox(
          width: double.maxFinite,
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
            ListTile(
              leading: const Icon(Icons.people, color: Colors.green),
              title: const Text('学生管理'),
              subtitle: const Text('查看当前设备导入的学生信息'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () {
                Navigator.pop(context);
                _showStudentManagementDialog();
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.lock, color: Colors.orange),
              title: const Text('修改密码'),
              subtitle: const Text('修改管理员登录密码'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () {
                Navigator.pop(context);
                _showChangePasswordDialog();
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.assignment, color: Colors.purple),
              title: const Text('考试状态管理'),
              subtitle: const Text('查看和管理所有考试状态'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () {
                Navigator.pop(context);
                _showExamStateManagementDialog();
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.bug_report, color: Colors.orange),
              title: const Text('调试：检查存储数据'),
              subtitle: const Text('查看SharedPreferences中的所有数据'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () {
                Navigator.pop(context);
                _debugCheckStorageData();
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.storage, color: Colors.purple),
              title: const Text('数据库查看器'),
              subtitle: const Text('查看系统中的所有数据（考试、学生、结果等）'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () {
                Navigator.pop(context);
                _showDatabaseViewer();
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.refresh, color: Colors.blue),
              title: const Text('调试：触发未完成考试检查'),
              subtitle: const Text('手动触发未完成考试检查逻辑'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () {
                Navigator.pop(context);
                _debugTriggerIncompleteExamCheck();
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.clear_all, color: Colors.red),
              title: const Text('清除所有本地数据'),
              subtitle: const Text('清除SharedPreferences中的所有数据'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () {
                Navigator.pop(context);
                _showClearAllDataDialog();
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.terminal, color: Colors.green),
              title: const Text('查看应用日志'),
              subtitle: const Text('查看应用内的调试日志信息'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () {
                Navigator.pop(context);
                _showAppLogsDialog();
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.bug_report, color: Colors.orange),
              title: const Text('测试学生恢复对话框'),
              subtitle: const Text('手动测试学生恢复考试对话框'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () {
                Navigator.pop(context);
                _testStudentRecoveryDialog();
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.delete_sweep, color: Colors.red),
              title: const Text('清除学生信息'),
              subtitle: const Text('清除所有学生数据，方便重新导入'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () {
                Navigator.pop(context);
                _showClearStudentsDialog();
              },
            ),
            const Divider(),
            ListTile(
              leading: const Icon(Icons.info, color: Colors.blue),
              title: const Text('关于系统'),
              subtitle: const Text('查看系统版本信息'),
              trailing: const Icon(Icons.arrow_forward_ios, size: 16),
              onTap: () {
                Navigator.pop(context);
                _showAboutDialog();
              },
            ),
              ],
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  // 显示修改密码对话框
  void _showChangePasswordDialog() {
    showDialog(
      context: context,
      builder: (context) => _ChangePasswordDialog(),
    );
  }

  // 显示清除学生信息对话框
  void _showClearStudentsDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Row(
          children: [
            Icon(Icons.warning, color: Colors.red),
            SizedBox(width: 8),
            Text('清除学生信息'),
          ],
        ),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '确认要清除所有学生信息吗？',
              style: TextStyle(
                fontSize: 16,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: 12),
            Text('此操作将：'),
            SizedBox(height: 8),
            Text('• 删除所有已导入的学生数据'),
            Text('• 清空学生登录记录'),
            Text('• 无法恢复已删除的数据'),
            SizedBox(height: 12),
            Text(
              '建议在重新导入学生信息前执行此操作。',
              style: TextStyle(
                fontSize: 12,
                color: Colors.orange,
                fontStyle: FontStyle.italic,
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              _showClearStudentsConfirmDialog();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: const Text('确认清除'),
          ),
        ],
      ),
    );
  }

  // 显示清除学生信息确认对话框（需要管理员密码）
  void _showClearStudentsConfirmDialog() {
    showDialog(
      context: context,
      builder: (context) => _ClearStudentsPasswordDialog(),
    );
  }

  // 显示学生管理对话框
  void _showStudentManagementDialog() {
    showDialog(
      context: context,
      builder: (context) => _StudentManagementDialog(),
    );
  }

  // 显示关于对话框
  void _showAboutDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Row(
          children: [
            Icon(Icons.info, color: Colors.blue),
            SizedBox(width: 8),
            Text('关于系统'),
          ],
        ),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '考培系统',
              style: TextStyle(
                fontSize: 18,
                fontWeight: FontWeight.bold,
              ),
            ),
            SizedBox(height: 8),
            Text('版本: 1.0.0'),
            SizedBox(height: 4),
            Text('构建日期: 2024-01-01'),
            SizedBox(height: 16),
            Text(
              '功能特性：',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 4),
            Text('• 在线考试管理'),
            Text('• 学生信息管理'),
            Text('• 考试结果导出'),
            Text('• 管理员密码修改'),
            Text('• 学生信息清除'),
            Text('• 考试暂停/恢复'),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }

  // 显示考试状态管理对话框
  void _showExamStateManagementDialog() {
    showDialog(
      context: context,
      builder: (context) => _ExamStateManagementDialog(),
    );
  }

  // 调试：检查存储数据
  Future<void> _debugCheckStorageData() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final allKeys = prefs.getKeys();

      debugPrint('=== SharedPreferences 调试信息 ===');
      debugPrint('总键数: ${allKeys.length}');

      // 按类型分组显示
      final examStateKeys = allKeys.where((key) => key.startsWith('exam_state_')).toList();
      final examResultKeys = allKeys.where((key) => key.startsWith('exam_result_')).toList();
      final otherKeys = allKeys.where((key) =>
        !key.startsWith('exam_state_') &&
        !key.startsWith('exam_result_')
      ).toList();

      debugPrint('考试状态键 (${examStateKeys.length}个):');
      for (var key in examStateKeys) {
        debugPrint('  - $key');
        try {
          final value = prefs.getString(key);
          if (value != null) {
            final stateMap = jsonDecode(value);
            final state = ExamState.fromJson(stateMap);
            debugPrint('    用户: ${state.userId}, 考试: ${state.examId}');
            debugPrint('    状态: ${state.status}, 剩余时间: ${state.remainingSeconds}秒');
            debugPrint('    最后更新: ${state.lastUpdated}');
            debugPrint('    活跃会话: ${state.answers.containsKey('_active_session') ? state.answers['_active_session'] : 'false'}');
            debugPrint('    答案数量: ${state.answers.length}');
          }
        } catch (e) {
          debugPrint('    解析失败: $e');
        }
      }

      debugPrint('考试结果键 (${examResultKeys.length}个):');
      for (var key in examResultKeys) {
        debugPrint('  - $key');
      }

      debugPrint('其他键 (${otherKeys.length}个):');
      for (var key in otherKeys) {
        debugPrint('  - $key');
      }

      // 显示给用户
      if (mounted) {
        showDialog(
          context: context,
          builder: (context) => AlertDialog(
            title: const Text('存储数据调试'),
            content: SingleChildScrollView(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  Text('总键数: ${allKeys.length}'),
                  const SizedBox(height: 8),
                  Text('考试状态: ${examStateKeys.length}个'),
                  Text('考试结果: ${examResultKeys.length}个'),
                  Text('其他数据: ${otherKeys.length}个'),
                  const SizedBox(height: 16),
                  const Text('详细信息请查看控制台日志'),
                ],
              ),
            ),
            actions: [
              TextButton(
                onPressed: () => Navigator.pop(context),
                child: const Text('关闭'),
              ),
            ],
          ),
        );
      }
    } catch (e) {
      debugPrint('调试检查存储数据失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('检查存储数据失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  // 调试：手动触发未完成考试检查
  Future<void> _debugTriggerIncompleteExamCheck() async {
    try {
      debugPrint('=== 管理员手动触发未完成考试检查 ===');

      // 直接调用检查方法
      await _checkIncompleteExams();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('未完成考试检查已触发，请查看控制台日志'),
            backgroundColor: Colors.blue,
          ),
        );
      }
    } catch (e) {
      debugPrint('触发未完成考试检查失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('触发检查失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  // 显示清除所有数据的确认对话框
  void _showClearAllDataDialog() {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Row(
          children: [
            Icon(Icons.warning, color: Colors.red),
            SizedBox(width: 8),
            Text('危险操作'),
          ],
        ),
        content: const Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              '确定要清除所有本地数据吗？',
              style: TextStyle(fontWeight: FontWeight.bold),
            ),
            SizedBox(height: 16),
            Text('此操作将清除：'),
            Text('• 所有考试状态'),
            Text('• 所有考试结果'),
            Text('• 所有学生数据'),
            Text('• 所有设备配置'),
            Text('• 其他应用数据'),
            SizedBox(height: 16),
            Text(
              '此操作不可撤销！',
              style: TextStyle(
                color: Colors.red,
                fontWeight: FontWeight.bold,
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              Navigator.pop(context);
              _clearAllData();
            },
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: const Text('确认清除'),
          ),
        ],
      ),
    );
  }

  // 清除所有SharedPreferences数据
  Future<void> _clearAllData() async {
    try {
      debugPrint('=== 开始清除所有本地数据 ===');

      final prefs = await SharedPreferences.getInstance();
      final allKeys = prefs.getKeys();

      debugPrint('清除前共有 ${allKeys.length} 个键');
      for (var key in allKeys) {
        debugPrint('  - $key');
      }

      // 清除所有数据
      await prefs.clear();

      debugPrint('✅ 所有本地数据已清除');

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('所有本地数据已清除'),
            backgroundColor: Colors.green,
          ),
        );

        // 显示重启提示
        showDialog(
          context: context,
          barrierDismissible: false,
          builder: (context) => AlertDialog(
            title: const Text('数据已清除'),
            content: const Text('所有本地数据已清除。建议重启应用以确保状态正确。'),
            actions: [
              ElevatedButton(
                onPressed: () {
                  Navigator.pop(context);
                  // 可以选择退出应用或重新初始化
                  SystemNavigator.pop(); // 退出应用
                },
                child: const Text('退出应用'),
              ),
            ],
          ),
        );
      }
    } catch (e) {
      debugPrint('❌ 清除数据失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('清除数据失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  // 显示应用日志对话框
  void _showAppLogsDialog() {
    showDialog(
      context: context,
      builder: (context) => _AppLogsDialog(),
    );
  }

  // 手动检查当前用户的考试状态
  Future<void> _debugCheckExamStatesForCurrentUser() async {
    try {
      final currentUser = UserData.currentUser;
      if (currentUser == null) {
        AppLogger.log('❌ 手动检查失败: 当前用户为空');
        return;
      }

      AppLogger.log('🔍 手动检查用户 ${currentUser.id} 的考试状态...');

      final prefs = await SharedPreferences.getInstance();
      final allKeys = prefs.getKeys();

      // 查找所有考试状态键
      final examStateKeys = allKeys.where((key) => key.startsWith('exam_state_')).toList();
      AppLogger.log('找到 ${examStateKeys.length} 个考试状态键:');

      for (var key in examStateKeys) {
        AppLogger.log('  - $key');

        // 检查是否包含当前用户ID
        if (key.contains(currentUser.id)) {
          AppLogger.log('    ✅ 匹配当前用户ID');

          try {
            final stateJson = prefs.getString(key);
            if (stateJson != null) {
              final stateMap = jsonDecode(stateJson);
              final state = ExamState.fromJson(stateMap);

              AppLogger.log('    考试状态详情:');
              AppLogger.log('      - 考试ID: "${state.examId}"');
              AppLogger.log('      - 考试ID长度: ${state.examId.length}');
              AppLogger.log('      - 用户ID: ${state.userId}');
              AppLogger.log('      - 状态: ${state.status}');
              AppLogger.log('      - 最后更新: ${state.lastUpdated}');
              AppLogger.log('      - 活跃会话: ${state.answers.containsKey('_active_session') ? state.answers['_active_session'] : 'false'}');

              // 检查这个考试ID是否在系统中存在
              final examExists = ExamService.getExamById(state.examId);
              AppLogger.log('      - 考试是否存在: ${examExists != null ? '是' : '否'}');
              if (examExists != null) {
                AppLogger.log('      - 考试标题: ${examExists.title}');
              }

              if (state.status != ExamStatus.completed) {
                AppLogger.log('    ⚠️ 发现未完成的考试状态！');

                // 如果发现未完成的考试，强制显示恢复对话框
                if (mounted) {
                  WidgetsBinding.instance.addPostFrameCallback((_) {
                    if (mounted) {
                      AppLogger.log('🚀 强制显示恢复对话框');
                      _showForceRecoveryDialog(state);
                    }
                  });
                }
              }
            }
          } catch (e) {
            AppLogger.log('    ❌ 解析考试状态失败: $e');
          }
        } else {
          AppLogger.log('    ❌ 不匹配当前用户ID');
        }
      }
    } catch (e) {
      AppLogger.log('❌ 手动检查考试状态失败: $e');
    }
  }

  // 强制显示恢复对话框 - 集成管理员密码验证
  void _showForceRecoveryDialog(ExamState state) {
    // 创建密码控制器
    final TextEditingController passwordController = TextEditingController();
    bool isPasswordVisible = false;

    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => StatefulBuilder(
        builder: (context, setState) => SingleChildScrollView(
          child: AlertDialog(
            title: Row(
              children: [
                Icon(Icons.restore, color: Colors.blue, size: 24),
                SizedBox(width: 8),
                Expanded(
                  child: Text(
                    '发现未完成考试',
                    style: TextStyle(fontSize: 16),
                  ),
                ),
              ],
            ),
            content: Container(
              width: double.maxFinite,
              child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    '检测到您有未完成的考试：',
                    style: TextStyle(fontSize: 14),
                  ),
                  SizedBox(height: 12),
                  // 考试信息卡片
                  Container(
                    padding: EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.blue.shade50,
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.blue.shade200),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        // 显示考试标题
                        Text(
                          state.examTitle,
                          style: TextStyle(
                            fontSize: 14,
                            fontWeight: FontWeight.bold,
                            color: Colors.blue.shade800,
                          ),
                        ),
                        SizedBox(height: 8),
                        Text(
                          '最后更新: ${_formatLastUpdatedTime(state.lastUpdated)}',
                          style: TextStyle(fontSize: 12, color: Colors.grey.shade600),
                        ),
                        SizedBox(height: 4),
                        Text(
                          '剩余时间: ${_formatTimeForRecovery(state.remainingSeconds)}',
                          style: TextStyle(fontSize: 12, color: Colors.orange.shade700),
                        ),
                        SizedBox(height: 4),
                        Text(
                          '已答题数: ${_calculateAnsweredQuestions(state.answers)}',
                          style: TextStyle(fontSize: 12, color: Colors.green.shade700),
                        ),
                      ],
                    ),
                  ),
                  SizedBox(height: 16),
                  // 管理员密码验证区域
                  Container(
                    padding: EdgeInsets.all(12),
                    decoration: BoxDecoration(
                      color: Colors.orange.shade50,
                      borderRadius: BorderRadius.circular(8),
                      border: Border.all(color: Colors.orange.shade200),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Row(
                          children: [
                            Icon(Icons.security, color: Colors.orange.shade700, size: 18),
                            SizedBox(width: 6),
                            Text(
                              '需要管理员密码验证',
                              style: TextStyle(
                                fontWeight: FontWeight.bold,
                                color: Colors.orange.shade700,
                                fontSize: 13,
                              ),
                            ),
                          ],
                        ),
                        SizedBox(height: 8),
                        Text(
                          '恢复考试需要管理员授权，请输入管理员密码：',
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey.shade700,
                          ),
                        ),
                        SizedBox(height: 10),
                        TextField(
                          controller: passwordController,
                          obscureText: !isPasswordVisible,
                          decoration: InputDecoration(
                            labelText: '管理员密码',
                            hintText: '请输入管理员密码',
                            prefixIcon: Icon(Icons.lock, size: 18),
                            suffixIcon: IconButton(
                              icon: Icon(
                                isPasswordVisible ? Icons.visibility : Icons.visibility_off,
                                size: 18,
                              ),
                              onPressed: () {
                                setState(() {
                                  isPasswordVisible = !isPasswordVisible;
                                });
                              },
                            ),
                            border: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(6),
                            ),
                            contentPadding: EdgeInsets.symmetric(horizontal: 10, vertical: 8),
                            isDense: true,
                          ),
                          style: TextStyle(fontSize: 13),
                        ),
                      ],
                    ),
                  ),
                ],
              ),
            ),
            actions: [
              TextButton(
                onPressed: () async {
                  passwordController.dispose();
                  Navigator.pop(context);
                  // 清除考试状态，重新开始
                  await ExamStateService.removeExamState(state.examId, state.userId);
                  AppLogger.log('用户选择重新开始，已清除考试状态');
                },
                style: TextButton.styleFrom(
                  padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                ),
                child: Text('重新开始', style: TextStyle(fontSize: 13)),
              ),
              ElevatedButton.icon(
                icon: Icon(Icons.play_arrow, size: 16),
                label: Text('恢复考试', style: TextStyle(fontSize: 13)),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  foregroundColor: Colors.white,
                  padding: EdgeInsets.symmetric(horizontal: 12, vertical: 6),
                ),
                onPressed: () {
                  final password = passwordController.text.trim();

                  if (password.isEmpty) {
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text('请输入管理员密码'),
                        backgroundColor: Colors.orange,
                      ),
                    );
                    return;
                  }

                  if (UserData.verifyAdminPassword(password)) {
                    // 密码验证成功
                    AppLogger.log('✅ 管理员密码验证成功，准备强制恢复考试');

                    // 将考试状态转换为兼容格式
                    // 动态获取考试标题
                    final exam = ExamService.getExamById(state.examId);
                    String examTitle = '未知考试';
                    int totalQuestions = 0;

                    if (exam != null) {
                      examTitle = exam.title;
                      totalQuestions = exam.questions.length;
                    } else {
                      // 如果精确匹配失败，尝试通过标题匹配
                      final allExams = ExamService.getAllExams();
                      final examByTitle = allExams.where((e) => e.title.contains('应用系统开发类试卷')).firstOrNull;
                      if (examByTitle != null) {
                        examTitle = examByTitle.title;
                        totalQuestions = examByTitle.questions.length;
                      }
                    }

                    final examData = {
                      'examId': state.examId,
                      'examTitle': examTitle,
                      'remainingSeconds': state.remainingSeconds,
                      'lastUpdated': state.lastUpdated.toString(),
                      'answerCount': state.answers.length,
                      'totalQuestions': totalQuestions,
                    };

                    // 关闭对话框
                    passwordController.dispose();
                    Navigator.pop(context);

                    // 显示成功提示
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text('管理员密码验证成功，正在恢复考试...'),
                        backgroundColor: Colors.green,
                        duration: Duration(seconds: 1),
                      ),
                    );

                    // 使用简单的延迟执行恢复操作，避免构建作用域冲突
                    Future.delayed(Duration(milliseconds: 800), () {
                      if (mounted) {
                        _resumeExamForStudent(examData);
                      }
                    });
                  } else {
                    // 密码错误
                    AppLogger.log('❌ 管理员密码验证失败');
                    ScaffoldMessenger.of(context).showSnackBar(
                      SnackBar(
                        content: Text('管理员密码错误，请重试'),
                        backgroundColor: Colors.red,
                      ),
                    );
                  }
                },
              ),
            ],
            actionsPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
          ),
        ),
      ),
    ).then((_) {
      // 确保对话框关闭时释放控制器
      try {
        passwordController.dispose();
      } catch (e) {
        // 忽略重复释放的错误
      }
    });
  }

  // 格式化时间显示（恢复对话框专用）
  String _formatTimeForRecovery(int seconds) {
    final hours = seconds ~/ 3600;
    final minutes = (seconds % 3600) ~/ 60;
    final secs = seconds % 60;
    return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
  }

  // 测试学生恢复对话框
  void _testStudentRecoveryDialog() {
    AppLogger.log('🧪 手动测试学生恢复对话框');

    // 创建一个模拟的考试数据
    final testExam = {
      'examId': 'test_exam_001',
      'examTitle': '测试考试',
      'remainingSeconds': 3600,
      'answerCount': 5,
      'totalQuestions': 20,
      'lastUpdated': DateTime.now().toIso8601String(),
    };

    AppLogger.log('模拟考试数据: $testExam');

    // 直接显示学生版对话框
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(Icons.warning_amber, color: Colors.red, size: 28),
            SizedBox(width: 10),
            Text('测试 - 发现未完成的考试', style: TextStyle(color: Colors.red.shade700)),
          ],
        ),
        content: Container(
          width: double.maxFinite,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                '这是一个测试对话框：',
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: 16),
              ),
              SizedBox(height: 16),
              Text(
                '点击下面的按钮应该有反应。',
                style: TextStyle(fontSize: 14, color: Colors.grey.shade700),
              ),
            ],
          ),
        ),
        actions: [
          ElevatedButton.icon(
            icon: Icon(Icons.play_arrow),
            label: Text('测试恢复考试'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.green,
              foregroundColor: Colors.white,
              padding: EdgeInsets.symmetric(horizontal: 16, vertical: 10),
            ),
            onPressed: () {
              AppLogger.log('🧪 测试按钮被点击');
              Navigator.pop(context);

              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(
                  content: Text('测试按钮工作正常！'),
                  backgroundColor: Colors.green,
                  duration: Duration(seconds: 3),
                ),
              );

              AppLogger.log('测试完成，按钮响应正常');
            },
          ),
        ],
        actionsPadding: EdgeInsets.symmetric(horizontal: 16, vertical: 12),
      ),
    );
  }

  // 显示数据库查看器
  void _showDatabaseViewer() {
    showDialog(
      context: context,
      builder: (context) => _DatabaseViewerDialog(),
    );
  }
}

// 应用日志查看对话框
class _AppLogsDialog extends StatefulWidget {
  @override
  _AppLogsDialogState createState() => _AppLogsDialogState();
}

class _AppLogsDialogState extends State<_AppLogsDialog> {
  final ScrollController _scrollController = ScrollController();
  List<String> _logs = [];
  String _searchQuery = '';
  List<String> _filteredLogs = [];

  @override
  void initState() {
    super.initState();
    _loadLogs();
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  void _loadLogs() {
    setState(() {
      _logs = AppLogger.getLogs();
      _filterLogs();
    });
  }

  void _filterLogs() {
    if (_searchQuery.isEmpty) {
      _filteredLogs = _logs;
    } else {
      _filteredLogs = _logs.where((log) =>
        log.toLowerCase().contains(_searchQuery.toLowerCase())
      ).toList();
    }
  }

  void _scrollToBottom() {
    if (_scrollController.hasClients) {
      _scrollController.animateTo(
        _scrollController.position.maxScrollExtent,
        duration: const Duration(milliseconds: 300),
        curve: Curves.easeOut,
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Container(
        width: MediaQuery.of(context).size.width * 0.9,
        height: MediaQuery.of(context).size.height * 0.8,
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // 标题栏
            Row(
              children: [
                const Icon(Icons.terminal, color: Colors.green),
                const SizedBox(width: 8),
                const Text(
                  '应用日志',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                IconButton(
                  icon: const Icon(Icons.refresh),
                  onPressed: _loadLogs,
                  tooltip: '刷新',
                ),
                IconButton(
                  icon: const Icon(Icons.vertical_align_bottom),
                  onPressed: _scrollToBottom,
                  tooltip: '滚动到底部',
                ),
                IconButton(
                  icon: const Icon(Icons.clear),
                  onPressed: () {
                    AppLogger.clearLogs();
                    _loadLogs();
                    ScaffoldMessenger.of(context).showSnackBar(
                      const SnackBar(
                        content: Text('日志已清除'),
                        backgroundColor: Colors.green,
                      ),
                    );
                  },
                  tooltip: '清除日志',
                ),
                IconButton(
                  icon: const Icon(Icons.close),
                  onPressed: () => Navigator.pop(context),
                  tooltip: '关闭',
                ),
              ],
            ),
            const Divider(),

            // 搜索栏
            Padding(
              padding: const EdgeInsets.only(bottom: 16),
              child: TextField(
                decoration: const InputDecoration(
                  hintText: '搜索日志...',
                  prefixIcon: Icon(Icons.search),
                  border: OutlineInputBorder(),
                ),
                onChanged: (value) {
                  setState(() {
                    _searchQuery = value;
                    _filterLogs();
                  });
                },
              ),
            ),

            // 统计信息
            Padding(
              padding: const EdgeInsets.only(bottom: 16),
              child: Row(
                children: [
                  Text('总日志: ${_logs.length}'),
                  const SizedBox(width: 16),
                  Text('显示: ${_filteredLogs.length}'),
                  const Spacer(),
                  if (_logs.isNotEmpty)
                    Text(
                      '最新: ${_logs.last.substring(1, 20)}',
                      style: const TextStyle(fontSize: 12, color: Colors.grey),
                    ),
                ],
              ),
            ),

            // 日志列表
            Expanded(
              child: _filteredLogs.isEmpty
                  ? const Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Icon(Icons.inbox, size: 64, color: Colors.grey),
                          SizedBox(height: 16),
                          Text('没有日志数据', style: TextStyle(color: Colors.grey)),
                        ],
                      ),
                    )
                  : ListView.builder(
                      controller: _scrollController,
                      itemCount: _filteredLogs.length,
                      itemBuilder: (context, index) {
                        final log = _filteredLogs[index];
                        final isError = log.contains('❌') || log.contains('错误') || log.contains('失败');
                        final isSuccess = log.contains('✅') || log.contains('成功');
                        final isWarning = log.contains('⚠️') || log.contains('警告');

                        Color? backgroundColor;
                        if (isError) {
                          backgroundColor = Colors.red.withOpacity(0.1);
                        } else if (isSuccess) {
                          backgroundColor = Colors.green.withOpacity(0.1);
                        } else if (isWarning) {
                          backgroundColor = Colors.orange.withOpacity(0.1);
                        }

                        return Container(
                          margin: const EdgeInsets.only(bottom: 4),
                          padding: const EdgeInsets.all(8),
                          decoration: BoxDecoration(
                            color: backgroundColor,
                            border: Border.all(
                              color: Colors.grey.withOpacity(0.3),
                            ),
                            borderRadius: BorderRadius.circular(4),
                          ),
                          child: SelectableText(
                            log,
                            style: TextStyle(
                              fontFamily: 'monospace',
                              fontSize: 12,
                              color: isError
                                  ? Colors.red.shade700
                                  : isSuccess
                                      ? Colors.green.shade700
                                      : isWarning
                                          ? Colors.orange.shade700
                                          : null,
                            ),
                          ),
                        );
                      },
                    ),
            ),
          ],
        ),
      ),
    );
  }
}

// 独立的清除学生信息密码验证对话框组件
class _ClearStudentsPasswordDialog extends StatefulWidget {
  @override
  _ClearStudentsPasswordDialogState createState() => _ClearStudentsPasswordDialogState();
}

class _ClearStudentsPasswordDialogState extends State<_ClearStudentsPasswordDialog> {
  final TextEditingController passwordController = TextEditingController();
  bool obscurePassword = true;

  @override
  void dispose() {
    passwordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Row(
        children: [
          Icon(Icons.security, color: Colors.orange),
          SizedBox(width: 8),
          Text('管理员验证'),
        ],
      ),
      content: Column(
        mainAxisSize: MainAxisSize.min,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Text(
            '请输入管理员密码以确认清除操作：',
            style: TextStyle(fontSize: 14),
          ),
          const SizedBox(height: 16),
          TextField(
            controller: passwordController,
            obscureText: obscurePassword,
            decoration: InputDecoration(
              labelText: '管理员密码',
              border: const OutlineInputBorder(),
              prefixIcon: const Icon(Icons.lock),
              suffixIcon: IconButton(
                icon: Icon(
                  obscurePassword ? Icons.visibility : Icons.visibility_off,
                ),
                onPressed: () {
                  setState(() {
                    obscurePassword = !obscurePassword;
                  });
                },
              ),
            ),
          ),
          const SizedBox(height: 8),
          const Text(
            '⚠️ 此操作不可撤销，请谨慎操作！',
            style: TextStyle(
              fontSize: 12,
              color: Colors.red,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: () {
            _handleClearStudents(context, passwordController.text);
          },
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.red,
            foregroundColor: Colors.white,
          ),
          child: const Text('确认清除'),
        ),
      ],
    );
  }

  // 处理清除学生信息
  void _handleClearStudents(BuildContext context, String password) async {
    // 验证管理员密码
    if (!UserData.verifyAdminPassword(password)) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('管理员密码错误，请重试'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    try {
      // 关闭密码验证对话框
      Navigator.pop(context);

      // 显示加载指示器
      showDialog(
        context: context,
        barrierDismissible: false,
        builder: (context) => const AlertDialog(
          content: Row(
            children: [
              CircularProgressIndicator(),
              SizedBox(width: 16),
              Text('正在清除学生信息...'),
            ],
          ),
        ),
      );

      // 清除学生数据
      final success = await StudentService.clearAllStudents();

      // 关闭加载指示器
      Navigator.pop(context);

      if (success) {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('学生信息已成功清除！'),
            backgroundColor: Colors.green,
          ),
        );
      } else {
        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('清除学生信息失败，请重试'),
            backgroundColor: Colors.red,
          ),
        );
      }
    } catch (e) {
      // 确保关闭加载指示器
      if (Navigator.canPop(context)) {
        Navigator.pop(context);
      }

      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('清除过程中发生错误：$e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
}

// 独立的密码修改对话框组件
class _ChangePasswordDialog extends StatefulWidget {
  @override
  _ChangePasswordDialogState createState() => _ChangePasswordDialogState();
}

class _ChangePasswordDialogState extends State<_ChangePasswordDialog> {
  final TextEditingController oldPasswordController = TextEditingController();
  final TextEditingController newPasswordController = TextEditingController();
  final TextEditingController confirmPasswordController = TextEditingController();
  bool obscureOldPassword = true;
  bool obscureNewPassword = true;
  bool obscureConfirmPassword = true;

  @override
  void dispose() {
    oldPasswordController.dispose();
    newPasswordController.dispose();
    confirmPasswordController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return AlertDialog(
      title: const Row(
        children: [
          Icon(Icons.lock, color: Colors.orange),
          SizedBox(width: 8),
          Text('修改管理员密码'),
        ],
      ),
      content: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            const Text(
              '请输入原密码和新密码：',
              style: TextStyle(
                fontSize: 14,
                color: Colors.grey,
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: oldPasswordController,
              obscureText: obscureOldPassword,
              decoration: InputDecoration(
                labelText: '原密码',
                border: const OutlineInputBorder(),
                prefixIcon: const Icon(Icons.lock_outline),
                suffixIcon: IconButton(
                  icon: Icon(
                    obscureOldPassword ? Icons.visibility : Icons.visibility_off,
                  ),
                  onPressed: () {
                    setState(() {
                      obscureOldPassword = !obscureOldPassword;
                    });
                  },
                ),
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: newPasswordController,
              obscureText: obscureNewPassword,
              decoration: InputDecoration(
                labelText: '新密码',
                border: const OutlineInputBorder(),
                prefixIcon: const Icon(Icons.lock),
                suffixIcon: IconButton(
                  icon: Icon(
                    obscureNewPassword ? Icons.visibility : Icons.visibility_off,
                  ),
                  onPressed: () {
                    setState(() {
                      obscureNewPassword = !obscureNewPassword;
                    });
                  },
                ),
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: confirmPasswordController,
              obscureText: obscureConfirmPassword,
              decoration: InputDecoration(
                labelText: '确认新密码',
                border: const OutlineInputBorder(),
                prefixIcon: const Icon(Icons.lock),
                suffixIcon: IconButton(
                  icon: Icon(
                    obscureConfirmPassword ? Icons.visibility : Icons.visibility_off,
                  ),
                  onPressed: () {
                    setState(() {
                      obscureConfirmPassword = !obscureConfirmPassword;
                    });
                  },
                ),
              ),
            ),
            const SizedBox(height: 8),
            const Text(
              '注意：修改密码后，所有需要管理员验证的功能都将使用新密码。',
              style: TextStyle(
                fontSize: 12,
                color: Colors.orange,
              ),
            ),
          ],
        ),
      ),
      actions: [
        TextButton(
          onPressed: () {
            Navigator.pop(context);
          },
          child: const Text('取消'),
        ),
        ElevatedButton(
          onPressed: () {
            _handlePasswordChange(context);
          },
          style: ElevatedButton.styleFrom(
            backgroundColor: Colors.blue,
            foregroundColor: Colors.white,
          ),
          child: const Text('确认修改'),
        ),
      ],
    );
  }

  // 处理密码修改
  void _handlePasswordChange(BuildContext context) {
    final String oldPassword = oldPasswordController.text;
    final String newPassword = newPasswordController.text;
    final String confirmPassword = confirmPasswordController.text;

    // 验证输入
    if (oldPassword.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请输入原密码'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    if (newPassword.isEmpty) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('请输入新密码'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    if (newPassword.length < 6) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('新密码长度不能少于6位'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    if (newPassword != confirmPassword) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('两次输入的新密码不一致'),
          backgroundColor: Colors.red,
        ),
      );
      return;
    }

    if (oldPassword == newPassword) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('新密码不能与原密码相同'),
          backgroundColor: Colors.orange,
        ),
      );
      return;
    }

    // 尝试修改密码
    bool success = UserData.changeAdminPassword(oldPassword, newPassword);

    if (success) {
      Navigator.pop(context);
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('密码修改成功！'),
          backgroundColor: Colors.green,
        ),
      );
    } else {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Text('原密码错误，请重试'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
}

// 完全独立的倒计时组件，有自己的定时器，不影响主页面
class _IndependentCountdownWidget extends StatefulWidget {
  final int initialSeconds;
  final VoidCallback onTimeout;
  final VoidCallback? onReset;

  const _IndependentCountdownWidget({
    Key? key,
    required this.initialSeconds,
    required this.onTimeout,
    this.onReset,
  }) : super(key: key);

  @override
  _IndependentCountdownWidgetState createState() => _IndependentCountdownWidgetState();
}

class _IndependentCountdownWidgetState extends State<_IndependentCountdownWidget> {
  late int _remainingSeconds;
  Timer? _timer;

  @override
  void initState() {
    super.initState();
    _remainingSeconds = widget.initialSeconds;
    _startTimer();
  }

  @override
  void dispose() {
    _timer?.cancel();
    super.dispose();
  }

  void _startTimer() {
    _timer?.cancel();
    _timer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (!mounted) {
        timer.cancel();
        return;
      }

      if (_remainingSeconds > 0) {
        // 使用PostFrameCallback确保在正确的构建周期执行setState
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            setState(() {
              _remainingSeconds--;
            });
          }
        });
      } else {
        _timer?.cancel();
        // 延迟执行回调，避免在构建过程中执行
        WidgetsBinding.instance.addPostFrameCallback((_) {
          if (mounted) {
            widget.onTimeout();
          }
        });
      }
    });
  }

  void resetTimer() {
    if (!mounted) return;

    // 使用PostFrameCallback确保在正确的构建周期执行
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (mounted) {
        setState(() {
          _remainingSeconds = widget.initialSeconds;
        });
        _startTimer();
        widget.onReset?.call();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: resetTimer, // 点击可以重置计时器
      child: Container(
        padding: EdgeInsets.symmetric(horizontal: 6, vertical: 3), // 减少padding
        margin: EdgeInsets.only(right: 4), // 减少margin
        decoration: BoxDecoration(
          color: _remainingSeconds <= 5 ? Colors.red.shade700 :
                _remainingSeconds <= 10 ? Colors.orange.shade700 :
                Colors.blue.shade700,
          borderRadius: BorderRadius.circular(16), // 减少圆角
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            Icon(Icons.timer, size: 14, color: Colors.white), // 减少图标大小
            SizedBox(width: 3), // 减少间距
            Flexible( // 添加Flexible包装文本
              child: Text(
                "${_remainingSeconds}s",
                style: TextStyle(
                  fontSize: 10, // 减少字体大小
                  fontWeight: FontWeight.bold,
                  color: Colors.white,
                ),
                overflow: TextOverflow.ellipsis,
                maxLines: 1,
              ),
            ),
          ],
        ),
      ),
    );
  }


}

// 学生管理对话框组件
class _StudentManagementDialog extends StatefulWidget {
  @override
  _StudentManagementDialogState createState() => _StudentManagementDialogState();
}

class _StudentManagementDialogState extends State<_StudentManagementDialog> {
  List<Student> _students = [];
  bool _isLoading = true;
  String _searchQuery = '';
  final TextEditingController _searchController = TextEditingController();

  @override
  void initState() {
    super.initState();
    _loadStudents();
  }

  @override
  void dispose() {
    _searchController.dispose();
    super.dispose();
  }

  // 加载学生数据
  void _loadStudents() async {
    try {
      final students = StudentService.getStudents();
      setState(() {
        _students = students;
        _isLoading = false;
      });
    } catch (e) {
      setState(() {
        _isLoading = false;
      });
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('加载学生信息失败：$e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }

  // 过滤学生列表
  List<Student> get _filteredStudents {
    if (_searchQuery.isEmpty) {
      return _students;
    }
    return _students.where((student) {
      final name = student.name.toLowerCase();
      final studentId = student.id.toLowerCase();
      final query = _searchQuery.toLowerCase();

      return name.contains(query) || studentId.contains(query);
    }).toList();
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Container(
        width: MediaQuery.of(context).size.width * 0.9,
        height: MediaQuery.of(context).size.height * 0.8,
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // 标题栏
            Row(
              children: [
                const Icon(Icons.people, color: Colors.green, size: 28),
                const SizedBox(width: 12),
                const Text(
                  '学生管理',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                IconButton(
                  onPressed: () => Navigator.pop(context),
                  icon: const Icon(Icons.close),
                ),
              ],
            ),
            const Divider(),

            // 搜索栏和统计信息
            Row(
              children: [
                Expanded(
                  child: TextField(
                    controller: _searchController,
                    decoration: const InputDecoration(
                      hintText: '搜索学生姓名或学号...',
                      prefixIcon: Icon(Icons.search),
                      border: OutlineInputBorder(),
                      contentPadding: EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                    ),
                    onChanged: (value) {
                      setState(() {
                        _searchQuery = value;
                      });
                    },
                  ),
                ),
                const SizedBox(width: 12),
                Container(
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                  decoration: BoxDecoration(
                    color: Colors.blue.shade50,
                    borderRadius: BorderRadius.circular(8),
                    border: Border.all(color: Colors.blue.shade200),
                  ),
                  child: Text(
                    '共 ${_students.length} 名学生',
                    style: TextStyle(
                      color: Colors.blue.shade700,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 16),

            // 学生列表
            Expanded(
              child: _isLoading
                  ? const Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          CircularProgressIndicator(),
                          SizedBox(height: 16),
                          Text('正在加载学生信息...'),
                        ],
                      ),
                    )
                  : _students.isEmpty
                      ? const Center(
                          child: Column(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              Icon(
                                Icons.people_outline,
                                size: 64,
                                color: Colors.grey,
                              ),
                              SizedBox(height: 16),
                              Text(
                                '暂无学生信息',
                                style: TextStyle(
                                  fontSize: 16,
                                  color: Colors.grey,
                                ),
                              ),
                              SizedBox(height: 8),
                              Text(
                                '请先导入学生数据',
                                style: TextStyle(
                                  fontSize: 14,
                                  color: Colors.grey,
                                ),
                              ),
                            ],
                          ),
                        )
                      : _buildStudentList(),
            ),

            // 底部操作栏
            const Divider(),
            Row(
              children: [
                ElevatedButton.icon(
                  onPressed: _loadStudents,
                  icon: const Icon(Icons.refresh),
                  label: const Text('刷新'),
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Colors.blue,
                    foregroundColor: Colors.white,
                  ),
                ),
                const Spacer(),
                TextButton(
                  onPressed: () => Navigator.pop(context),
                  child: const Text('关闭'),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  // 构建学生列表
  Widget _buildStudentList() {
    final filteredStudents = _filteredStudents;

    if (filteredStudents.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(
              Icons.search_off,
              size: 64,
              color: Colors.grey,
            ),
            SizedBox(height: 16),
            Text(
              '未找到匹配的学生',
              style: TextStyle(
                fontSize: 16,
                color: Colors.grey,
              ),
            ),
          ],
        ),
      );
    }

    return ListView.builder(
      itemCount: filteredStudents.length,
      itemBuilder: (context, index) {
        final student = filteredStudents[index];
        return Card(
          margin: const EdgeInsets.only(bottom: 8),
          child: ListTile(
            leading: CircleAvatar(
              backgroundColor: Colors.blue.shade100,
              child: Text(
                student.name.isNotEmpty ? student.name.substring(0, 1) : '?',
                style: TextStyle(
                  color: Colors.blue.shade700,
                  fontWeight: FontWeight.bold,
                ),
              ),
            ),
            title: Text(
              student.name.isNotEmpty ? student.name : '未知姓名',
              style: const TextStyle(fontWeight: FontWeight.bold),
            ),
            subtitle: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text('学号: ${student.id}'),
                if (student.email != null && student.email!.isNotEmpty)
                  Text('邮箱: ${student.email}'),
                if (student.idCardNumber.isNotEmpty)
                  Text('身份证: ${student.idCardNumber}'),
              ],
            ),
            trailing: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Icon(
                  Icons.person,
                  color: Colors.green.shade600,
                ),
                const SizedBox(height: 4),
                Text(
                  '学生',
                  style: TextStyle(
                    fontSize: 12,
                    color: Colors.green.shade600,
                  ),
                ),
              ],
            ),
            onTap: () => _showStudentDetail(student),
          ),
        );
      },
    );
  }

  // 显示学生详情
  void _showStudentDetail(Student student) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            const Icon(Icons.person, color: Colors.blue),
            const SizedBox(width: 8),
            Text(student.name.isNotEmpty ? student.name : '学生详情'),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            _buildDetailRow('姓名', student.name.isNotEmpty ? student.name : '未知'),
            _buildDetailRow('学号', student.id),
            _buildDetailRow('身份证号', student.idCardNumber.isNotEmpty ? student.idCardNumber : '未知'),
            if (student.email != null && student.email!.isNotEmpty)
              _buildDetailRow('邮箱', student.email!),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  // 构建详情行
  Widget _buildDetailRow(String label, String value) {
    return Padding(
      padding: const EdgeInsets.only(bottom: 8),
      child: Row(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          SizedBox(
            width: 80,
            child: Text(
              '$label:',
              style: const TextStyle(
                fontWeight: FontWeight.bold,
                color: Colors.grey,
              ),
            ),
          ),
          Expanded(
            child: Text(value),
          ),
        ],
      ),
    );
  }
}

// 考试状态管理对话框
class _ExamStateManagementDialog extends StatefulWidget {
  @override
  _ExamStateManagementDialogState createState() => _ExamStateManagementDialogState();
}

class _ExamStateManagementDialogState extends State<_ExamStateManagementDialog> {
  List<Map<String, dynamic>> _allExamStates = [];
  List<Map<String, dynamic>> _allExamResults = [];
  bool _isLoading = true;

  @override
  void initState() {
    super.initState();
    _loadAllExamData();
  }

  Future<void> _loadAllExamData() async {
    setState(() {
      _isLoading = true;
    });

    try {
      // 获取所有考试状态和结果
      await _loadAllExamStates();
      await _loadAllExamResults();
    } catch (e) {
      debugPrint('加载考试数据失败: $e');
    }

    setState(() {
      _isLoading = false;
    });
  }

  // 检查是否存在考试结果
  Future<bool> _checkIfExamResultExists(String examId, String userId) async {
    try {
      // 1. 检查SharedPreferences中的结果
      final prefs = await SharedPreferences.getInstance();
      final resultKey = 'exam_result_${examId}_$userId';
      if (prefs.containsKey(resultKey)) {
        debugPrint('在SharedPreferences中找到考试结果: $resultKey');
        return true;
      }

      // 2. 检查ExamService中的结果
      final serviceResult = ExamService.getUserExamResult(examId, userId);
      if (serviceResult != null) {
        debugPrint('在ExamService中找到考试结果: $examId - $userId');
        return true;
      }

      return false;
    } catch (e) {
      debugPrint('检查考试结果时出错: $e');
      return false;
    }
  }

  // 清理已完成考试的状态
  Future<void> _cleanupCompletedStates() async {
    try {
      // 显示确认对话框
      final confirmed = await showDialog<bool>(
        context: context,
        builder: (context) => AlertDialog(
          title: const Text('确认清理'),
          content: const Text('这将删除所有已完成考试的状态记录。已完成的考试结果不会受影响。\n\n确定要继续吗？'),
          actions: [
            TextButton(
              onPressed: () => Navigator.pop(context, false),
              child: const Text('取消'),
            ),
            ElevatedButton(
              onPressed: () => Navigator.pop(context, true),
              child: const Text('确定'),
              style: ElevatedButton.styleFrom(
                backgroundColor: Colors.orange,
                foregroundColor: Colors.white,
              ),
            ),
          ],
        ),
      );

      if (confirmed != true) return;

      // 执行清理
      final cleanedCount = await ExamStateService.cleanupCompletedExamStates();

      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('清理完成，共清理了 $cleanedCount 个已完成考试的状态'),
            backgroundColor: Colors.green,
            duration: const Duration(seconds: 3),
          ),
        );
      }

      // 重新加载数据
      _loadAllExamData();
    } catch (e) {
      debugPrint('清理已完成考试状态失败: $e');
      if (mounted) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('清理失败: $e'),
            backgroundColor: Colors.red,
            duration: const Duration(seconds: 3),
          ),
        );
      }
    }
  }

  Future<void> _loadAllExamStates() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final allKeys = prefs.getKeys();
      final List<Map<String, dynamic>> states = [];

      // 筛选出所有考试状态键
      final stateKeys = allKeys.where((key) =>
        key.startsWith('exam_state_')
      ).toList();

      debugPrint('找到 ${stateKeys.length} 个考试状态键');

      for (final key in stateKeys) {
        try {
          final String? stateJson = prefs.getString(key);
          if (stateJson != null) {
            final Map<String, dynamic> stateMap = jsonDecode(stateJson);
            final ExamState state = ExamState.fromJson(stateMap);

            // 检查是否已经有考试结果（如果有结果，说明考试已完成，不应该显示在状态列表中）
            final hasResult = await _checkIfExamResultExists(state.examId, state.userId);
            if (hasResult) {
              debugPrint('跳过已完成的考试状态: ${state.examId} - ${state.userId}');
              continue; // 跳过已完成的考试
            }

            // 获取考试详情
            final exam = ExamService.getExamById(state.examId);
            final student = StudentService.getStudentById(state.userId);

            states.add({
              'key': key,
              'examId': state.examId,
              'examTitle': exam?.title ?? '未知考试',
              'userId': state.userId,
              'userName': student?.name ?? '未知学生',
              'status': state.status.toString(),
              'remainingSeconds': state.remainingSeconds,
              'lastUpdated': state.lastUpdated.toIso8601String(),
              'answerCount': state.answers.length,
              'hasActiveSession': state.answers.containsKey('_active_session'),
              'activeSessionValue': state.answers['_active_session'],
            });
          }
        } catch (e) {
          debugPrint('处理考试状态出错: $key, 错误: $e');
        }
      }

      setState(() {
        _allExamStates = states;
      });
    } catch (e) {
      debugPrint('加载考试状态失败: $e');
    }
  }

  Future<void> _loadAllExamResults() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final allKeys = prefs.getKeys();
      final List<Map<String, dynamic>> results = [];

      // 筛选出所有考试结果键
      final resultKeys = allKeys.where((key) =>
        key.startsWith('exam_result_')
      ).toList();

      debugPrint('找到 ${resultKeys.length} 个考试结果键');

      for (final key in resultKeys) {
        try {
          final String? resultJson = prefs.getString(key);
          if (resultJson != null) {
            final Map<String, dynamic> resultMap = jsonDecode(resultJson);
            final ExamResult result = ExamResult.fromJson(resultMap);

            // 获取考试详情
            final exam = ExamService.getExamById(result.examId);
            final student = StudentService.getStudentById(result.userId);

            results.add({
              'key': key,
              'examId': result.examId,
              'examTitle': exam?.title ?? '未知考试',
              'userId': result.userId,
              'userName': student?.name ?? '未知学生',
              'score': result.totalScore,
              'submittedAt': result.submittedAt?.toIso8601String() ?? DateTime.now().toIso8601String(),
            });
          }
        } catch (e) {
          debugPrint('处理考试结果出错: $key, 错误: $e');
        }
      }

      setState(() {
        _allExamResults = results;
      });
    } catch (e) {
      debugPrint('加载考试结果失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Container(
        width: MediaQuery.of(context).size.width * 0.9,
        height: MediaQuery.of(context).size.height * 0.8,
        padding: const EdgeInsets.all(16),
        child: Column(
          children: [
            // 标题栏
            Row(
              children: [
                const Icon(Icons.assignment, color: Colors.purple),
                const SizedBox(width: 8),
                const Text(
                  '考试状态管理',
                  style: TextStyle(
                    fontSize: 20,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const Spacer(),
                IconButton(
                  icon: const Icon(Icons.refresh),
                  onPressed: _loadAllExamData,
                  tooltip: '刷新',
                ),
                IconButton(
                  icon: const Icon(Icons.close),
                  onPressed: () => Navigator.pop(context),
                  tooltip: '关闭',
                ),
              ],
            ),
            const Divider(),

            // 内容区域
            Expanded(
              child: _isLoading
                  ? const Center(child: CircularProgressIndicator())
                  : DefaultTabController(
                      length: 2,
                      child: Column(
                        children: [
                          const TabBar(
                            tabs: [
                              Tab(text: '考试状态', icon: Icon(Icons.pending_actions)),
                              Tab(text: '考试结果', icon: Icon(Icons.assignment_turned_in)),
                            ],
                          ),
                          Expanded(
                            child: TabBarView(
                              children: [
                                _buildExamStatesTab(),
                                _buildExamResultsTab(),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _buildExamStatesTab() {
    if (_allExamStates.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.inbox, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text('没有找到考试状态数据', style: TextStyle(color: Colors.grey)),
          ],
        ),
      );
    }

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '共找到 ${_allExamStates.length} 个考试状态',
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              ElevatedButton.icon(
                onPressed: _cleanupCompletedStates,
                icon: const Icon(Icons.cleaning_services, size: 16),
                label: const Text('清理已完成'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.orange,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                ),
              ),
            ],
          ),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: _allExamStates.length,
            itemBuilder: (context, index) {
              final state = _allExamStates[index];
              final lastUpdated = DateTime.parse(state['lastUpdated']);
              final timeDiff = DateTime.now().difference(lastUpdated).inMinutes;

              return Card(
                margin: const EdgeInsets.only(bottom: 8),
                child: ExpansionTile(
                  leading: Icon(
                    state['hasActiveSession'] == true
                        ? Icons.play_circle
                        : Icons.pause_circle,
                    color: state['hasActiveSession'] == true
                        ? Colors.green
                        : Colors.orange,
                  ),
                  title: Text(
                    '${state['userName']} - ${state['examTitle']}',
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('状态: ${state['status']}'),
                      Text('剩余时间: ${_formatSeconds(state['remainingSeconds'])}'),
                      Text('最后更新: ${timeDiff}分钟前'),
                      if (state['hasActiveSession'] == true)
                        Text(
                          '活跃会话: ${state['activeSessionValue']}',
                          style: const TextStyle(color: Colors.green),
                        ),
                    ],
                  ),
                  children: [
                    Padding(
                      padding: const EdgeInsets.all(16),
                      child: Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text('存储键: ${state['key']}'),
                          Text('考试ID: ${state['examId']}'),
                          Text('用户ID: ${state['userId']}'),
                          Text('已答题数: ${state['answerCount']}'),
                          const SizedBox(height: 8),
                          Row(
                            children: [
                              ElevatedButton(
                                onPressed: () => _deleteExamState(state['key']),
                                style: ElevatedButton.styleFrom(
                                  backgroundColor: Colors.red,
                                  foregroundColor: Colors.white,
                                ),
                                child: const Text('删除状态'),
                              ),
                              const SizedBox(width: 8),
                              if (state['hasActiveSession'] == true)
                                ElevatedButton(
                                  onPressed: () => _clearActiveSession(state),
                                  style: ElevatedButton.styleFrom(
                                    backgroundColor: Colors.orange,
                                    foregroundColor: Colors.white,
                                  ),
                                  child: const Text('清除活跃标记'),
                                ),
                            ],
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  Widget _buildExamResultsTab() {
    if (_allExamResults.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.inbox, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text('没有找到考试结果数据', style: TextStyle(color: Colors.grey)),
          ],
        ),
      );
    }

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(8.0),
          child: Text(
            '共找到 ${_allExamResults.length} 个考试结果',
            style: const TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: _allExamResults.length,
            itemBuilder: (context, index) {
              final result = _allExamResults[index];
              final submittedAt = DateTime.parse(result['submittedAt']);

              return Card(
                margin: const EdgeInsets.only(bottom: 8),
                child: ListTile(
                  leading: const Icon(Icons.assignment_turned_in, color: Colors.green),
                  title: Text(
                    '${result['userName']} - ${result['examTitle']}',
                    style: const TextStyle(fontWeight: FontWeight.bold),
                  ),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('得分: ${result['score']}'),
                      Text('提交时间: ${submittedAt.toString().substring(0, 19)}'),
                      Text('用户ID: ${result['userId']}'),
                    ],
                  ),
                  trailing: IconButton(
                    icon: const Icon(Icons.delete, color: Colors.red),
                    onPressed: () => _deleteExamResult(result['key']),
                  ),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  String _formatSeconds(int seconds) {
    final hours = seconds ~/ 3600;
    final minutes = (seconds % 3600) ~/ 60;
    final secs = seconds % 60;
    return '${hours.toString().padLeft(2, '0')}:${minutes.toString().padLeft(2, '0')}:${secs.toString().padLeft(2, '0')}';
  }

  Future<void> _deleteExamState(String key) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这个考试状态吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () => Navigator.pop(context, true),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        final prefs = await SharedPreferences.getInstance();
        await prefs.remove(key);

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('考试状态已删除'),
            backgroundColor: Colors.green,
          ),
        );

        _loadAllExamData(); // 重新加载数据
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('删除失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  Future<void> _deleteExamResult(String key) async {
    final confirmed = await showDialog<bool>(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('确认删除'),
        content: const Text('确定要删除这个考试结果吗？此操作不可撤销。'),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context, false),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () => Navigator.pop(context, true),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );

    if (confirmed == true) {
      try {
        final prefs = await SharedPreferences.getInstance();
        await prefs.remove(key);

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('考试结果已删除'),
            backgroundColor: Colors.green,
          ),
        );

        _loadAllExamData(); // 重新加载数据
      } catch (e) {
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Text('删除失败: $e'),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  Future<void> _clearActiveSession(Map<String, dynamic> stateInfo) async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final String? stateJson = prefs.getString(stateInfo['key']);

      if (stateJson != null) {
        final Map<String, dynamic> stateMap = jsonDecode(stateJson);
        final ExamState state = ExamState.fromJson(stateMap);

        // 创建新的答案映射，移除活跃会话标记
        final Map<String, dynamic> updatedAnswers = Map<String, dynamic>.from(state.answers);
        updatedAnswers.remove('_active_session');

        // 创建更新后的状态
        final updatedState = ExamState(
          examId: state.examId,
          userId: state.userId,
          examTitle: state.examTitle,
          answers: updatedAnswers,
          remainingSeconds: state.remainingSeconds,
          lastUpdated: DateTime.now(),
          status: state.status,
        );

        // 保存更新后的状态
        final updatedStateJson = jsonEncode(updatedState.toJson());
        await prefs.setString(stateInfo['key'], updatedStateJson);

        ScaffoldMessenger.of(context).showSnackBar(
          const SnackBar(
            content: Text('活跃会话标记已清除'),
            backgroundColor: Colors.green,
          ),
        );

        _loadAllExamData(); // 重新加载数据
      }
    } catch (e) {
      ScaffoldMessenger.of(context).showSnackBar(
        SnackBar(
          content: Text('清除活跃标记失败: $e'),
          backgroundColor: Colors.red,
        ),
      );
    }
  }
}

// 数据库查看器对话框
class _DatabaseViewerDialog extends StatefulWidget {
  @override
  _DatabaseViewerDialogState createState() => _DatabaseViewerDialogState();
}

class _DatabaseViewerDialogState extends State<_DatabaseViewerDialog>
    with SingleTickerProviderStateMixin {
  late TabController _tabController;
  bool _isLoading = true;

  // 数据存储
  List<Map<String, dynamic>> _examStates = [];
  List<Map<String, dynamic>> _examResults = [];
  List<Map<String, dynamic>> _exams = [];
  List<Map<String, dynamic>> _students = [];
  Map<String, String> _otherData = {};

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 5, vsync: this);
    _loadAllData();
  }

  @override
  void dispose() {
    _tabController.dispose();
    super.dispose();
  }

  Future<void> _loadAllData() async {
    try {
      setState(() {
        _isLoading = true;
      });

      await Future.wait([
        _loadSharedPreferencesData(),
        _loadExamServiceData(),
        _loadStudentServiceData(),
      ]);

      setState(() {
        _isLoading = false;
      });
    } catch (e) {
      debugPrint('加载数据失败: $e');
      setState(() {
        _isLoading = false;
      });
    }
  }

  // 加载SharedPreferences数据
  Future<void> _loadSharedPreferencesData() async {
    try {
      final prefs = await SharedPreferences.getInstance();
      final allKeys = prefs.getKeys();

      // 考试状态 - 保存原始JSON数据
      final stateKeys = allKeys.where((key) => key.startsWith('exam_state_')).toList();
      _examStates.clear();
      for (final key in stateKeys) {
        try {
          final stateJson = prefs.getString(key);
          if (stateJson != null) {
            // 格式化JSON以便阅读
            final stateMap = jsonDecode(stateJson);
            final formattedJson = JsonEncoder.withIndent('  ').convert(stateMap);
            _examStates.add({
              'key': key,
              'rawData': formattedJson,
              'dataType': 'ExamState',
              'size': stateJson.length,
            });
          }
        } catch (e) {
          final rawValue = prefs.getString(key) ?? '';
          _examStates.add({
            'key': key,
            'rawData': rawValue,
            'dataType': 'Invalid JSON',
            'error': e.toString(),
            'size': rawValue.length,
          });
        }
      }

      // 考试结果 - 保存原始JSON数据
      final resultKeys = allKeys.where((key) => key.startsWith('exam_result_')).toList();
      _examResults.clear();
      for (final key in resultKeys) {
        try {
          final resultJson = prefs.getString(key);
          if (resultJson != null) {
            // 格式化JSON以便阅读
            final resultMap = jsonDecode(resultJson);
            final formattedJson = JsonEncoder.withIndent('  ').convert(resultMap);
            _examResults.add({
              'key': key,
              'rawData': formattedJson,
              'dataType': 'ExamResult',
              'size': resultJson.length,
            });
          }
        } catch (e) {
          final rawValue = prefs.getString(key) ?? '';
          _examResults.add({
            'key': key,
            'rawData': rawValue,
            'dataType': 'Invalid JSON',
            'error': e.toString(),
            'size': rawValue.length,
          });
        }
      }

      // 其他数据 - 保存原始数据
      final otherKeys = allKeys.where((key) =>
        !key.startsWith('exam_state_') &&
        !key.startsWith('exam_result_')
      ).toList();

      _otherData.clear();
      for (final key in otherKeys) {
        final value = prefs.get(key);
        String rawData;
        String dataType;

        if (value is String) {
          // 尝试格式化JSON字符串
          try {
            final jsonData = jsonDecode(value);
            rawData = JsonEncoder.withIndent('  ').convert(jsonData);
            dataType = 'JSON String';
          } catch (e) {
            rawData = value;
            dataType = 'String';
          }
        } else {
          rawData = value.toString();
          dataType = value.runtimeType.toString();
        }

        _otherData[key] = '$dataType|$rawData';
      }
    } catch (e) {
      debugPrint('加载SharedPreferences数据失败: $e');
    }
  }

  // 加载ExamService数据
  Future<void> _loadExamServiceData() async {
    try {
      _exams.clear();
      final allExams = ExamService.getAllExams();
      for (final exam in allExams) {
        // 将Exam对象转换为JSON格式显示
        final examJson = {
          'id': exam.id,
          'title': exam.title,
          'description': exam.description,
          'duration': exam.duration,
          'totalScore': exam.totalScore,
          'originalId': exam.originalId,
          'sequence': exam.sequence,
          'questions': exam.questions.map((q) => {
            'id': q.id,
            'type': q.type.toString(),
            'text': q.text,
            'score': q.score,
            'analysis': q.analysis,
            // 根据题目类型添加特定字段
            if (q is SingleChoiceQuestion) ...{
              'choices': q.choices.map((c) => c.toJson()).toList(),
              'correctOption': q.correctOption,
            },
            if (q is MultipleChoiceQuestion) ...{
              'choices': q.choices.map((c) => c.toJson()).toList(),
              'correctOptions': q.correctOptions,
            },
            if (q is TrueOrFalseQuestion) ...{
              'correctAnswer': q.correctAnswer,
            },
            if (q is FillBlankQuestion) ...{
              'correctAnswer': q.correctAnswer,
              'correctAnswers': q.correctAnswers,
              'blankCount': q.blankCount,
            },
            if (q is ShortAnswerQuestion) ...{
              'referencedAnswer': q.referencedAnswer,
            },
          }).toList(),
        };

        // 添加考试结果统计
        final examResults = ExamService.getExamResults(exam.id);
        examJson['resultCount'] = examResults.length;
        examJson['avgScore'] = examResults.isEmpty ? 0.0 :
          examResults.map((r) => r.totalScore).reduce((a, b) => a + b) / examResults.length;

        // 格式化JSON
        final formattedJson = const JsonEncoder.withIndent('  ').convert(examJson);
        _exams.add({
          'key': 'exam_${exam.id}',
          'rawData': formattedJson,
          'dataType': 'Exam',
          'size': formattedJson.length,
        });
      }
    } catch (e) {
      debugPrint('加载ExamService数据失败: $e');
    }
  }

  // 加载StudentService数据
  Future<void> _loadStudentServiceData() async {
    try {
      _students.clear();
      final allStudents = StudentService.getStudents();
      for (final student in allStudents) {
        // 将Student对象转换为JSON格式显示
        final studentJson = {
          'id': student.id,
          'name': student.name,
          'role': student.role,
          'idCardNumber': student.idCardNumber,
          'email': student.email,
          'avatar': student.avatar,
          'assignedExamId': student.assignedExamId,
        };

        // 格式化JSON
        final formattedJson = const JsonEncoder.withIndent('  ').convert(studentJson);
        _students.add({
          'key': 'student_${student.id}',
          'rawData': formattedJson,
          'dataType': 'Student',
          'size': formattedJson.length,
        });
      }
    } catch (e) {
      debugPrint('加载StudentService数据失败: $e');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Dialog(
      child: Container(
        width: MediaQuery.of(context).size.width * 0.9,
        height: MediaQuery.of(context).size.height * 0.8,
        child: Column(
          children: [
            // 标题栏
            Container(
              padding: const EdgeInsets.all(16),
              decoration: BoxDecoration(
                color: Colors.blue.shade50,
                borderRadius: const BorderRadius.only(
                  topLeft: Radius.circular(4),
                  topRight: Radius.circular(4),
                ),
              ),
              child: Row(
                children: [
                  const Icon(Icons.storage, color: Colors.blue),
                  const SizedBox(width: 8),
                  const Text(
                    '数据库查看器',
                    style: TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                  const Spacer(),
                  IconButton(
                    onPressed: () => Navigator.pop(context),
                    icon: const Icon(Icons.close),
                  ),
                ],
              ),
            ),
            // 内容区域
            Expanded(
              child: _isLoading
                  ? const Center(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          CircularProgressIndicator(),
                          SizedBox(height: 16),
                          Text('正在加载数据...'),
                        ],
                      ),
                    )
                  : Column(
                      children: [
                        // 标签栏
                        TabBar(
                          controller: _tabController,
                          isScrollable: true,
                          tabs: const [
                            Tab(text: '考试状态', icon: Icon(Icons.pending_actions)),
                            Tab(text: '考试结果', icon: Icon(Icons.assignment_turned_in)),
                            Tab(text: '考试信息', icon: Icon(Icons.quiz)),
                            Tab(text: '学生信息', icon: Icon(Icons.people)),
                            Tab(text: '其他数据', icon: Icon(Icons.more_horiz)),
                          ],
                        ),
                        // 标签页内容
                        Expanded(
                          child: TabBarView(
                            controller: _tabController,
                            children: [
                              _buildExamStatesView(),
                              _buildExamResultsView(),
                              _buildExamsView(),
                              _buildStudentsView(),
                              _buildOtherDataView(),
                            ],
                          ),
                        ),
                      ],
                    ),
            ),
          ],
        ),
      ),
    );
  }

  // 构建考试状态视图
  Widget _buildExamStatesView() {
    if (_examStates.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.inbox, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text('没有考试状态数据', style: TextStyle(color: Colors.grey)),
          ],
        ),
      );
    }

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(16),
          child: Text(
            '共找到 ${_examStates.length} 个考试状态',
            style: const TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: _examStates.length,
            itemBuilder: (context, index) {
              final state = _examStates[index];
              final key = state['key'] ?? '未知键';
              final rawData = state['rawData'] ?? '';
              final dataType = state['dataType'] ?? 'Unknown';
              final size = state['size'] ?? 0;
              final hasError = state.containsKey('error');

              return Card(
                margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                child: ListTile(
                  title: Text(key),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('类型: $dataType'),
                      Text('大小: ${size} 字符'),
                      if (hasError)
                        Text('错误: ${state['error']}', style: const TextStyle(color: Colors.red)),
                      const SizedBox(height: 4),
                      Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: Colors.grey.shade100,
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          rawData.length > 200 ? '${rawData.substring(0, 200)}...' : rawData,
                          style: const TextStyle(fontFamily: 'monospace', fontSize: 11),
                          maxLines: 6,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                  leading: Icon(
                    hasError ? Icons.error : Icons.timer,
                    color: hasError ? Colors.red : Colors.orange,
                  ),
                  onTap: () => _showDataDetail(key, rawData),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  // 构建考试结果视图
  Widget _buildExamResultsView() {
    if (_examResults.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.inbox, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text('没有考试结果数据', style: TextStyle(color: Colors.grey)),
          ],
        ),
      );
    }

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(16),
          child: Text(
            '共找到 ${_examResults.length} 个考试结果',
            style: const TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: _examResults.length,
            itemBuilder: (context, index) {
              final result = _examResults[index];
              final key = result['key'] ?? '未知键';
              final rawData = result['rawData'] ?? '';
              final dataType = result['dataType'] ?? 'Unknown';
              final size = result['size'] ?? 0;
              final hasError = result.containsKey('error');

              return Card(
                margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                child: ListTile(
                  title: Text(key),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('类型: $dataType'),
                      Text('大小: $size 字符'),
                      if (hasError)
                        Text('错误: ${result['error']}', style: const TextStyle(color: Colors.red)),
                      const SizedBox(height: 4),
                      Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: Colors.grey.shade100,
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          rawData.length > 200 ? '${rawData.substring(0, 200)}...' : rawData,
                          style: const TextStyle(fontFamily: 'monospace', fontSize: 11),
                          maxLines: 6,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                  leading: Icon(
                    hasError ? Icons.error : Icons.assignment_turned_in,
                    color: hasError ? Colors.red : Colors.green,
                  ),
                  onTap: () => _showDataDetail(key, rawData),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  // 构建考试信息视图
  Widget _buildExamsView() {
    if (_exams.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.inbox, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text('没有考试数据', style: TextStyle(color: Colors.grey)),
          ],
        ),
      );
    }

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(16),
          child: Text(
            '共找到 ${_exams.length} 个考试',
            style: const TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: _exams.length,
            itemBuilder: (context, index) {
              final exam = _exams[index];
              final key = exam['key'] ?? '未知键';
              final rawData = exam['rawData'] ?? '';
              final dataType = exam['dataType'] ?? 'Unknown';
              final size = exam['size'] ?? 0;

              return Card(
                margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                child: ListTile(
                  title: Text(key),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('类型: $dataType'),
                      Text('大小: $size 字符'),
                      const SizedBox(height: 4),
                      Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: Colors.grey.shade100,
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          rawData.length > 200 ? '${rawData.substring(0, 200)}...' : rawData,
                          style: const TextStyle(fontFamily: 'monospace', fontSize: 11),
                          maxLines: 6,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                  leading: const Icon(Icons.quiz, color: Colors.blue),
                  onTap: () => _showDataDetail(key, rawData),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  // 构建学生信息视图
  Widget _buildStudentsView() {
    if (_students.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.inbox, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text('没有学生数据', style: TextStyle(color: Colors.grey)),
          ],
        ),
      );
    }

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(16),
          child: Text(
            '共找到 ${_students.length} 个学生',
            style: const TextStyle(fontWeight: FontWeight.bold),
          ),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: _students.length,
            itemBuilder: (context, index) {
              final student = _students[index];
              final key = student['key'] ?? '未知键';
              final rawData = student['rawData'] ?? '';
              final dataType = student['dataType'] ?? 'Unknown';
              final size = student['size'] ?? 0;

              return Card(
                margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                child: ListTile(
                  title: Text(key),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('类型: $dataType'),
                      Text('大小: $size 字符'),
                      const SizedBox(height: 4),
                      Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: Colors.grey.shade100,
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          rawData.length > 200 ? '${rawData.substring(0, 200)}...' : rawData,
                          style: const TextStyle(fontFamily: 'monospace', fontSize: 11),
                          maxLines: 6,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                  leading: const Icon(Icons.person, color: Colors.green),
                  onTap: () => _showDataDetail(key, rawData),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  // 构建其他数据视图
  Widget _buildOtherDataView() {
    if (_otherData.isEmpty) {
      return const Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Icon(Icons.inbox, size: 64, color: Colors.grey),
            SizedBox(height: 16),
            Text('没有其他数据', style: TextStyle(color: Colors.grey)),
          ],
        ),
      );
    }

    return Column(
      children: [
        Padding(
          padding: const EdgeInsets.all(16),
          child: Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            children: [
              Text(
                '共找到 ${_otherData.length} 个其他数据项',
                style: const TextStyle(fontWeight: FontWeight.bold),
              ),
              ElevatedButton.icon(
                onPressed: _loadAllData,
                icon: const Icon(Icons.refresh, size: 16),
                label: const Text('刷新'),
                style: ElevatedButton.styleFrom(
                  backgroundColor: Colors.blue,
                  foregroundColor: Colors.white,
                  padding: const EdgeInsets.symmetric(horizontal: 12, vertical: 8),
                ),
              ),
            ],
          ),
        ),
        Expanded(
          child: ListView.builder(
            itemCount: _otherData.length,
            itemBuilder: (context, index) {
              final key = _otherData.keys.elementAt(index);
              final fullValue = _otherData[key]!;

              // 解析数据类型和原始数据
              final parts = fullValue.split('|');
              final dataType = parts.length > 1 ? parts[0] : 'Unknown';
              final rawData = parts.length > 1 ? parts[1] : fullValue;

              return Card(
                margin: const EdgeInsets.symmetric(horizontal: 16, vertical: 4),
                child: ListTile(
                  title: Text(key),
                  subtitle: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text('类型: $dataType'),
                      Text('大小: ${rawData.length} 字符'),
                      const SizedBox(height: 4),
                      Container(
                        padding: const EdgeInsets.all(8),
                        decoration: BoxDecoration(
                          color: Colors.grey.shade100,
                          borderRadius: BorderRadius.circular(4),
                        ),
                        child: Text(
                          rawData.length > 200 ? '${rawData.substring(0, 200)}...' : rawData,
                          style: const TextStyle(fontFamily: 'monospace', fontSize: 11),
                          maxLines: 6,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ),
                    ],
                  ),
                  leading: const Icon(Icons.data_object, color: Colors.purple),
                  onTap: () => _showDataDetail(key, rawData),
                ),
              );
            },
          ),
        ),
      ],
    );
  }

  // 显示数据详情
  void _showDataDetail(String key, String value) {
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Text('数据详情'),
        content: Container(
          width: double.maxFinite,
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text('键: $key', style: const TextStyle(fontWeight: FontWeight.bold)),
              const SizedBox(height: 8),
              Text('值:', style: const TextStyle(fontWeight: FontWeight.bold)),
              const SizedBox(height: 4),
              Container(
                padding: const EdgeInsets.all(8),
                decoration: BoxDecoration(
                  color: Colors.grey.shade100,
                  borderRadius: BorderRadius.circular(4),
                ),
                child: SingleChildScrollView(
                  child: Text(
                    value,
                    style: const TextStyle(fontFamily: 'monospace', fontSize: 12),
                  ),
                ),
              ),
            ],
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('关闭'),
          ),
          TextButton(
            onPressed: () {
              Clipboard.setData(ClipboardData(text: value));
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('已复制到剪贴板')),
              );
            },
            child: const Text('复制'),
          ),
        ],
      ),
    );
  }
}